3 * @defgroup Parser Parser
7 * File for Parser and related classes
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
18 * There are five main entry points into the Parser class:
20 * produces HTML output
22 * produces altered wiki markup.
24 * removes HTML comments and expands templates
26 * Cleans a signature before saving it to preferences
28 * Extracts sections from an article for section editing
31 * objects: $wgLang, $wgContLang
33 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
36 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
37 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
38 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
41 * * only within ParserOptions
49 * Update this version number when the ParserOutput format
50 * changes in an incompatible way, so the parser cache
51 * can automatically discard old data.
53 const VERSION
= '1.6.4';
55 # Flags for Parser::setFunctionHook
56 # Also available as global constants from Defines.php
57 const SFH_NO_HASH
= 1;
58 const SFH_OBJECT_ARGS
= 2;
60 # Constants needed for external link processing
61 # Everything except bracket, space, or control characters
62 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
63 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
64 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
66 // State constants for the definition list colon extraction
67 const COLON_STATE_TEXT
= 0;
68 const COLON_STATE_TAG
= 1;
69 const COLON_STATE_TAGSTART
= 2;
70 const COLON_STATE_CLOSETAG
= 3;
71 const COLON_STATE_TAGSLASH
= 4;
72 const COLON_STATE_COMMENT
= 5;
73 const COLON_STATE_COMMENTDASH
= 6;
74 const COLON_STATE_COMMENTDASHDASH
= 7;
76 // Flags for preprocessToDom
77 const PTD_FOR_INCLUSION
= 1;
79 // Allowed values for $this->mOutputType
80 // Parameter to startExternalParse().
83 const OT_PREPROCESS
= 3;
86 // Marker Suffix needs to be accessible staticly.
87 const MARKER_SUFFIX
= "-QINU\x7f";
93 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
94 $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex, $mPreprocessor,
95 $mExtLinkBracketedRegex, $mUrlProtocols, $mDefaultStripList, $mVarCache, $mConf;
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
100 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mLinkHolders, $mLinkID;
102 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
103 var $mTplExpandCache; // empty-frame expansion cache
104 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
105 var $mExpensiveFunctionCount; // number of expensive parser function calls
109 # These are variables reset at least once per parse regardless of $clearState
110 var $mOptions, // ParserOptions object
111 $mTitle, // Title context, used for self-link rendering and similar things
112 $mOutputType, // Output type, one of the OT_xxx constants
113 $ot, // Shortcut alias, see setOutputType()
114 $mRevisionId, // ID to display in {{REVISIONID}} tags
115 $mRevisionTimestamp, // The timestamp of the specified revision ID
116 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
125 function __construct( $conf = array() ) {
126 $this->mConf
= $conf;
127 $this->mTagHooks
= array();
128 $this->mTransparentTagHooks
= array();
129 $this->mFunctionHooks
= array();
130 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
131 $this->mDefaultStripList
= $this->mStripList
= array( 'nowiki', 'gallery', 'poem' );
132 $this->mUrlProtocols
= wfUrlProtocols();
133 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
134 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
135 $this->mVarCache
= array();
136 if ( isset( $conf['preprocessorClass'] ) ) {
137 $this->mPreprocessorClass
= $conf['preprocessorClass'];
138 } elseif ( extension_loaded( 'domxml' ) ) {
139 // PECL extension that conflicts with the core DOM extension (bug 13770)
140 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
141 $this->mPreprocessorClass
= 'Preprocessor_Hash';
142 } elseif ( extension_loaded( 'dom' ) ) {
143 $this->mPreprocessorClass
= 'Preprocessor_DOM';
145 $this->mPreprocessorClass
= 'Preprocessor_Hash';
147 $this->mMarkerIndex
= 0;
148 $this->mFirstCall
= true;
152 * Reduce memory usage to reduce the impact of circular references
154 function __destruct() {
155 if ( isset( $this->mLinkHolders
) ) {
156 $this->mLinkHolders
->__destruct();
158 foreach ( $this as $name => $value ) {
159 unset( $this->$name );
164 * Do various kinds of initialisation on the first call of the parser
166 function firstCallInit() {
167 if ( !$this->mFirstCall
) {
170 $this->mFirstCall
= false;
172 wfProfileIn( __METHOD__
);
174 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
175 CoreParserFunctions
::register( $this );
176 $this->initialiseVariables();
178 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
179 wfProfileOut( __METHOD__
);
187 function clearState() {
188 wfProfileIn( __METHOD__
);
189 if ( $this->mFirstCall
) {
190 $this->firstCallInit();
192 $this->mOutput
= new ParserOutput
;
193 $this->mAutonumber
= 0;
194 $this->mLastSection
= '';
195 $this->mDTopen
= false;
196 $this->mIncludeCount
= array();
197 $this->mStripState
= new StripState
;
198 $this->mArgStack
= false;
199 $this->mInPre
= false;
200 $this->mLinkHolders
= new LinkHolderArray( $this );
202 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
205 * Prefix for temporary replacement strings for the multipass parser.
206 * \x07 should never appear in input as it's disallowed in XML.
207 * Using it at the front also gives us a little extra robustness
208 * since it shouldn't match when butted up against identifier-like
211 * Must not consist of all title characters, or else it will change
212 * the behaviour of <nowiki> in a link.
214 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
215 # Changed to \x7f to allow XML double-parsing -- TS
216 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
219 # Clear these on every parse, bug 4549
220 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
222 $this->mShowToc
= true;
223 $this->mForceTocPosition
= false;
224 $this->mIncludeSizes
= array(
228 $this->mPPNodeCount
= 0;
229 $this->mDefaultSort
= false;
230 $this->mHeadings
= array();
231 $this->mDoubleUnderscores
= array();
232 $this->mExpensiveFunctionCount
= 0;
233 $this->mFileCache
= array();
236 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
237 $this->mPreprocessor
= null;
240 wfRunHooks( 'ParserClearState', array( &$this ) );
241 wfProfileOut( __METHOD__
);
244 function setOutputType( $ot ) {
245 $this->mOutputType
= $ot;
248 'html' => $ot == self
::OT_HTML
,
249 'wiki' => $ot == self
::OT_WIKI
,
250 'pre' => $ot == self
::OT_PREPROCESS
,
255 * Set the context title
257 function setTitle( $t ) {
258 if ( !$t ||
$t instanceof FakeTitle
) {
259 $t = Title
::newFromText( 'NO TITLE' );
261 if ( strval( $t->getFragment() ) !== '' ) {
262 # Strip the fragment to avoid various odd effects
263 $this->mTitle
= clone $t;
264 $this->mTitle
->setFragment( '' );
271 * Accessor for mUniqPrefix.
275 function uniqPrefix() {
276 if( !isset( $this->mUniqPrefix
) ) {
277 // @fixme this is probably *horribly wrong*
278 // LanguageConverter seems to want $wgParser's uniqPrefix, however
279 // if this is called for a parser cache hit, the parser may not
280 // have ever been initialized in the first place.
281 // Not really sure what the heck is supposed to be going on here.
283 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
285 return $this->mUniqPrefix
;
289 * Convert wikitext to HTML
290 * Do not call this function recursively.
292 * @param $text String: text we want to parse
293 * @param $title A title object
294 * @param $options ParserOptions
295 * @param $linestart boolean
296 * @param $clearState boolean
297 * @param $revid Int: number to pass in {{REVISIONID}}
298 * @return ParserOutput a ParserOutput
300 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
302 * First pass--just handle <nowiki> sections, pass the rest off
303 * to internalParse() which does all the real work.
306 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
307 $fname = __METHOD__
.'-' . wfGetCaller();
308 wfProfileIn( __METHOD__
);
309 wfProfileIn( $fname );
315 $this->mOptions
= $options;
316 $this->setTitle( $title );
317 $oldRevisionId = $this->mRevisionId
;
318 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
319 if( $revid !== null ) {
320 $this->mRevisionId
= $revid;
321 $this->mRevisionTimestamp
= null;
323 $this->setOutputType( self
::OT_HTML
);
324 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
326 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
327 $text = $this->internalParse( $text );
328 $text = $this->mStripState
->unstripGeneral( $text );
330 # Clean up special characters, only run once, next-to-last before doBlockLevels
332 # french spaces, last one Guillemet-left
333 # only if there is something before the space
334 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
335 # french spaces, Guillemet-right
336 '/(\\302\\253) /' => '\\1 ',
337 '/ (!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
339 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
341 $text = $this->doBlockLevels( $text, $linestart );
343 $this->replaceLinkHolders( $text );
345 # the position of the parserConvert() call should not be changed. it
346 # assumes that the links are all replaced and the only thing left
347 # is the <nowiki> mark.
348 # Side-effects: this calls $this->mOutput->setTitleText()
349 $text = $wgContLang->parserConvert( $text, $this );
351 $text = $this->mStripState
->unstripNoWiki( $text );
353 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
355 //!JF Move to its own function
357 $uniq_prefix = $this->mUniqPrefix
;
359 $elements = array_keys( $this->mTransparentTagHooks
);
360 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
362 foreach( $matches as $marker => $data ) {
363 list( $element, $content, $params, $tag ) = $data;
364 $tagName = strtolower( $element );
365 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
366 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
367 array( $content, $params, $this ) );
371 $this->mStripState
->general
->setPair( $marker, $output );
373 $text = $this->mStripState
->unstripGeneral( $text );
375 $text = Sanitizer
::normalizeCharReferences( $text );
377 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
378 $text = self
::tidy($text);
380 # attempt to sanitize at least some nesting problems
381 # (bug #2702 and quite a few others)
383 # ''Something [http://www.cool.com cool''] -->
384 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
385 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
386 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
387 # fix up an anchor inside another anchor, only
388 # at least for a single single nested link (bug 3695)
389 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
390 '\\1\\2</a>\\3</a>\\1\\4</a>',
391 # fix div inside inline elements- doBlockLevels won't wrap a line which
392 # contains a div, so fix it up here; replace
393 # div with escaped text
394 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
395 '\\1\\3<div\\5>\\6</div>\\8\\9',
396 # remove empty italic or bold tag pairs, some
397 # introduced by rules above
398 '/<([bi])><\/\\1>/' => '',
401 $text = preg_replace(
402 array_keys( $tidyregs ),
403 array_values( $tidyregs ),
406 global $wgExpensiveParserFunctionLimit;
407 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
408 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
411 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
413 # Information on include size limits, for the benefit of users who try to skirt them
414 if ( $this->mOptions
->getEnableLimitReport() ) {
415 global $wgExpensiveParserFunctionLimit;
416 $max = $this->mOptions
->getMaxIncludeSize();
417 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
419 "NewPP limit report\n" .
420 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
421 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
422 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
424 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
425 $text .= "\n<!-- \n$limitReport-->\n";
427 $this->mOutput
->setText( $text );
428 $this->mRevisionId
= $oldRevisionId;
429 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
430 wfProfileOut( $fname );
431 wfProfileOut( __METHOD__
);
433 return $this->mOutput
;
437 * Recursive parser entry point that can be called from an extension tag
440 function recursiveTagParse( $text ) {
441 wfProfileIn( __METHOD__
);
442 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
443 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
444 $text = $this->internalParse( $text );
445 wfProfileOut( __METHOD__
);
450 * Expand templates and variables in the text, producing valid, static wikitext.
451 * Also removes comments.
453 function preprocess( $text, $title, $options, $revid = null ) {
454 wfProfileIn( __METHOD__
);
456 $this->setOutputType( self
::OT_PREPROCESS
);
457 $this->mOptions
= $options;
458 $this->setTitle( $title );
459 if( $revid !== null ) {
460 $this->mRevisionId
= $revid;
462 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
463 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
464 $text = $this->replaceVariables( $text );
465 $text = $this->mStripState
->unstripBoth( $text );
466 wfProfileOut( __METHOD__
);
471 * Get a random string
476 function getRandomString() {
477 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
480 function &getTitle() { return $this->mTitle
; }
481 function getOptions() { return $this->mOptions
; }
482 function getRevisionId() { return $this->mRevisionId
; }
483 function getOutput() { return $this->mOutput
; }
484 function nextLinkID() { return $this->mLinkID++
; }
486 function getFunctionLang() {
487 global $wgLang, $wgContLang;
489 $target = $this->mOptions
->getTargetLanguage();
490 if ( $target !== null ) {
493 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
498 * Get a preprocessor object
500 function getPreprocessor() {
501 if ( !isset( $this->mPreprocessor
) ) {
502 $class = $this->mPreprocessorClass
;
503 $this->mPreprocessor
= new $class( $this );
505 return $this->mPreprocessor
;
509 * Replaces all occurrences of HTML-style comments and the given tags
510 * in the text with a random marker and returns the next text. The output
511 * parameter $matches will be an associative array filled with data in
513 * 'UNIQ-xxxxx' => array(
516 * array( 'param' => 'x' ),
517 * '<element param="x">tag content</element>' ) )
519 * @param $elements list of element names. Comments are always extracted.
520 * @param $text Source text string.
521 * @param $uniq_prefix
526 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
531 $taglist = implode( '|', $elements );
532 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
534 while ( '' != $text ) {
535 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
537 if( count( $p ) < 5 ) {
540 if( count( $p ) > 5 ) {
554 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . self
::MARKER_SUFFIX
;
555 $stripped .= $marker;
557 if ( $close === '/>' ) {
558 // Empty element tag, <tag />
563 if( $element === '!--' ) {
566 $end = "/(<\\/$element\\s*>)/i";
568 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
570 if( count( $q ) < 3 ) {
571 # No end tag -- let it run out to the end of the text.
580 $matches[$marker] = array( $element,
582 Sanitizer
::decodeTagAttributes( $attributes ),
583 "<$element$attributes$close$content$tail" );
589 * Get a list of strippable XML-like elements
591 function getStripList() {
593 $elements = $this->mStripList
;
595 $elements[] = 'html';
597 if( $this->mOptions
->getUseTeX() ) {
598 $elements[] = 'math';
604 * @deprecated use replaceVariables
606 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
611 * Restores pre, math, and other extensions removed by strip()
613 * always call unstripNoWiki() after this one
615 * @deprecated use $this->mStripState->unstrip()
617 function unstrip( $text, $state ) {
618 return $state->unstripGeneral( $text );
622 * Always call this after unstrip() to preserve the order
625 * @deprecated use $this->mStripState->unstrip()
627 function unstripNoWiki( $text, $state ) {
628 return $state->unstripNoWiki( $text );
632 * @deprecated use $this->mStripState->unstripBoth()
634 function unstripForHTML( $text ) {
635 return $this->mStripState
->unstripBoth( $text );
639 * Add an item to the strip state
640 * Returns the unique tag which must be inserted into the stripped text
641 * The tag will be replaced with the original text in unstrip()
645 function insertStripItem( $text ) {
646 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
647 $this->mMarkerIndex++
;
648 $this->mStripState
->general
->setPair( $rnd, $text );
653 * Interface with html tidy, used if $wgUseTidy = true.
654 * If tidy isn't able to correct the markup, the original will be
655 * returned in all its glory with a warning comment appended.
657 * Either the external tidy program or the in-process tidy extension
658 * will be used depending on availability. Override the default
659 * $wgTidyInternal setting to disable the internal if it's not working.
661 * @param string $text Hideous HTML input
662 * @return string Corrected HTML output
666 function tidy( $text ) {
667 global $wgTidyInternal;
668 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
669 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
670 '<head><title>test</title></head><body>'.$text.'</body></html>';
671 if( $wgTidyInternal ) {
672 $correctedtext = self
::internalTidy( $wrappedtext );
674 $correctedtext = self
::externalTidy( $wrappedtext );
676 if( is_null( $correctedtext ) ) {
677 wfDebug( "Tidy error detected!\n" );
678 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
680 return $correctedtext;
684 * Spawn an external HTML tidy process and get corrected markup back from it.
689 function externalTidy( $text ) {
690 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
691 wfProfileIn( __METHOD__
);
696 $descriptorspec = array(
697 0 => array('pipe', 'r'),
698 1 => array('pipe', 'w'),
699 2 => array('file', wfGetNull(), 'a')
702 if( function_exists('proc_open') ) {
703 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
704 if (is_resource($process)) {
705 // Theoretically, this style of communication could cause a deadlock
706 // here. If the stdout buffer fills up, then writes to stdin could
707 // block. This doesn't appear to happen with tidy, because tidy only
708 // writes to stdout after it's finished reading from stdin. Search
709 // for tidyParseStdin and tidySaveStdout in console/tidy.c
710 fwrite($pipes[0], $text);
712 while (!feof($pipes[1])) {
713 $cleansource .= fgets($pipes[1], 1024);
716 proc_close($process);
720 wfProfileOut( __METHOD__
);
722 if( $cleansource == '' && $text != '') {
723 // Some kind of error happened, so we couldn't get the corrected text.
724 // Just give up; we'll use the source text and append a warning.
732 * Use the HTML tidy PECL extension to use the tidy library in-process,
733 * saving the overhead of spawning a new process.
735 * 'pear install tidy' should be able to compile the extension module.
740 function internalTidy( $text ) {
741 global $wgTidyConf, $IP, $wgDebugTidy;
742 wfProfileIn( __METHOD__
);
745 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
746 $tidy->cleanRepair();
747 if( $tidy->getStatus() == 2 ) {
748 // 2 is magic number for fatal error
749 // http://www.php.net/manual/en/function.tidy-get-status.php
752 $cleansource = tidy_get_output( $tidy );
754 if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
755 $cleansource .= "<!--\nTidy reports:\n" .
756 str_replace( '-->', '-->', $tidy->errorBuffer
) .
760 wfProfileOut( __METHOD__
);
765 * parse the wiki syntax used to render tables
769 function doTableStuff ( $text ) {
770 wfProfileIn( __METHOD__
);
772 $lines = StringUtils
::explode( "\n", $text );
774 $td_history = array (); // Is currently a td tag open?
775 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
776 $tr_history = array (); // Is currently a tr tag open?
777 $tr_attributes = array (); // history of tr attributes
778 $has_opened_tr = array(); // Did this table open a <tr> element?
779 $indent_level = 0; // indent level of the table
781 foreach ( $lines as $outLine ) {
782 $line = trim( $outLine );
784 if( $line == '' ) { // empty line, go to next line
785 $out .= $outLine."\n";
788 $first_character = $line[0];
791 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
792 // First check if we are starting a new table
793 $indent_level = strlen( $matches[1] );
795 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
796 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
798 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
799 array_push ( $td_history , false );
800 array_push ( $last_tag_history , '' );
801 array_push ( $tr_history , false );
802 array_push ( $tr_attributes , '' );
803 array_push ( $has_opened_tr , false );
804 } else if ( count ( $td_history ) == 0 ) {
805 // Don't do any of the following
806 $out .= $outLine."\n";
808 } else if ( substr ( $line , 0 , 2 ) === '|}' ) {
809 // We are ending a table
810 $line = '</table>' . substr ( $line , 2 );
811 $last_tag = array_pop ( $last_tag_history );
813 if ( !array_pop ( $has_opened_tr ) ) {
814 $line = "<tr><td></td></tr>{$line}";
817 if ( array_pop ( $tr_history ) ) {
818 $line = "</tr>{$line}";
821 if ( array_pop ( $td_history ) ) {
822 $line = "</{$last_tag}>{$line}";
824 array_pop ( $tr_attributes );
825 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
826 } else if ( substr ( $line , 0 , 2 ) === '|-' ) {
827 // Now we have a table row
828 $line = preg_replace( '#^\|-+#', '', $line );
830 // Whats after the tag is now only attributes
831 $attributes = $this->mStripState
->unstripBoth( $line );
832 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
833 array_pop ( $tr_attributes );
834 array_push ( $tr_attributes , $attributes );
837 $last_tag = array_pop ( $last_tag_history );
838 array_pop ( $has_opened_tr );
839 array_push ( $has_opened_tr , true );
841 if ( array_pop ( $tr_history ) ) {
845 if ( array_pop ( $td_history ) ) {
846 $line = "</{$last_tag}>{$line}";
850 array_push ( $tr_history , false );
851 array_push ( $td_history , false );
852 array_push ( $last_tag_history , '' );
854 else if ( $first_character === '|' ||
$first_character === '!' ||
substr ( $line , 0 , 2 ) === '|+' ) {
855 // This might be cell elements, td, th or captions
856 if ( substr ( $line , 0 , 2 ) === '|+' ) {
857 $first_character = '+';
858 $line = substr ( $line , 1 );
861 $line = substr ( $line , 1 );
863 if ( $first_character === '!' ) {
864 $line = str_replace ( '!!' , '||' , $line );
867 // Split up multiple cells on the same line.
868 // FIXME : This can result in improper nesting of tags processed
869 // by earlier parser steps, but should avoid splitting up eg
870 // attribute values containing literal "||".
871 $cells = StringUtils
::explodeMarkup( '||' , $line );
875 // Loop through each table cell
876 foreach ( $cells as $cell )
879 if ( $first_character !== '+' )
881 $tr_after = array_pop ( $tr_attributes );
882 if ( !array_pop ( $tr_history ) ) {
883 $previous = "<tr{$tr_after}>\n";
885 array_push ( $tr_history , true );
886 array_push ( $tr_attributes , '' );
887 array_pop ( $has_opened_tr );
888 array_push ( $has_opened_tr , true );
891 $last_tag = array_pop ( $last_tag_history );
893 if ( array_pop ( $td_history ) ) {
894 $previous = "</{$last_tag}>{$previous}";
897 if ( $first_character === '|' ) {
899 } else if ( $first_character === '!' ) {
901 } else if ( $first_character === '+' ) {
902 $last_tag = 'caption';
907 array_push ( $last_tag_history , $last_tag );
909 // A cell could contain both parameters and data
910 $cell_data = explode ( '|' , $cell , 2 );
912 // Bug 553: Note that a '|' inside an invalid link should not
913 // be mistaken as delimiting cell parameters
914 if ( strpos( $cell_data[0], '[[' ) !== false ) {
915 $cell = "{$previous}<{$last_tag}>{$cell}";
916 } else if ( count ( $cell_data ) == 1 )
917 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
919 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
920 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
921 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
925 array_push ( $td_history , true );
928 $out .= $outLine . "\n";
931 // Closing open td, tr && table
932 while ( count ( $td_history ) > 0 )
934 if ( array_pop ( $td_history ) ) {
937 if ( array_pop ( $tr_history ) ) {
940 if ( !array_pop ( $has_opened_tr ) ) {
941 $out .= "<tr><td></td></tr>\n" ;
944 $out .= "</table>\n";
947 // Remove trailing line-ending (b/c)
948 if ( substr( $out, -1 ) === "\n" ) {
949 $out = substr( $out, 0, -1 );
952 // special case: don't return empty table
953 if( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
957 wfProfileOut( __METHOD__
);
963 * Helper function for parse() that transforms wiki markup into
964 * HTML. Only called for $mOutputType == self::OT_HTML.
968 function internalParse( $text ) {
970 wfProfileIn( __METHOD__
);
972 # Hook to suspend the parser in this state
973 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
974 wfProfileOut( __METHOD__
);
978 $text = $this->replaceVariables( $text );
979 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
980 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
982 // Tables need to come after variable replacement for things to work
983 // properly; putting them before other transformations should keep
984 // exciting things like link expansions from showing up in surprising
986 $text = $this->doTableStuff( $text );
988 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
990 $text = $this->doDoubleUnderscore( $text );
991 $text = $this->doHeadings( $text );
992 if($this->mOptions
->getUseDynamicDates()) {
993 $df = DateFormatter
::getInstance();
994 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
996 $text = $this->doAllQuotes( $text );
997 $text = $this->replaceInternalLinks( $text );
998 $text = $this->replaceExternalLinks( $text );
1000 # replaceInternalLinks may sometimes leave behind
1001 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1002 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
1004 $text = $this->doMagicLinks( $text );
1005 $text = $this->formatHeadings( $text, $isMain );
1007 wfProfileOut( __METHOD__
);
1012 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1013 * magic external links.
1018 function doMagicLinks( $text ) {
1019 wfProfileIn( __METHOD__
);
1020 $prots = $this->mUrlProtocols
;
1021 $urlChar = self
::EXT_LINK_URL_CLASS
;
1022 $text = preg_replace_callback(
1024 (<a.*?</a>) | # m[1]: Skip link text
1025 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1026 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1027 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1028 ISBN\s+(\b # m[5]: ISBN, capture number
1029 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1030 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1031 [0-9Xx] # check digit
1033 )!x', array( &$this, 'magicLinkCallback' ), $text );
1034 wfProfileOut( __METHOD__
);
1038 function magicLinkCallback( $m ) {
1039 if ( isset( $m[1] ) && strval( $m[1] ) !== '' ) {
1042 } elseif ( isset( $m[2] ) && strval( $m[2] ) !== '' ) {
1045 } elseif ( isset( $m[3] ) && strval( $m[3] ) !== '' ) {
1046 # Free external link
1047 return $this->makeFreeExternalLink( $m[0] );
1048 } elseif ( isset( $m[4] ) && strval( $m[4] ) !== '' ) {
1050 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1054 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1056 $urlmsg = 'pubmedurl';
1059 throw new MWException( __METHOD__
.': unrecognised match type "' .
1060 substr($m[0], 0, 20 ) . '"' );
1062 $url = wfMsg( $urlmsg, $id);
1063 $sk = $this->mOptions
->getSkin();
1064 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1065 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1066 } elseif ( isset( $m[5] ) && strval( $m[5] ) !== '' ) {
1069 $num = strtr( $isbn, array(
1074 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1076 $titleObj->escapeLocalUrl() .
1077 "\" class=\"internal\">ISBN $isbn</a>";
1084 * Make a free external link, given a user-supplied URL
1088 function makeFreeExternalLink( $url ) {
1090 wfProfileIn( __METHOD__
);
1092 $sk = $this->mOptions
->getSkin();
1095 # The characters '<' and '>' (which were escaped by
1096 # removeHTMLtags()) should not be included in
1097 # URLs, per RFC 2396.
1099 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1100 $trail = substr($url, $m2[0][1]) . $trail;
1101 $url = substr($url, 0, $m2[0][1]);
1104 # Move trailing punctuation to $trail
1106 # If there is no left bracket, then consider right brackets fair game too
1107 if ( strpos( $url, '(' ) === false ) {
1111 $numSepChars = strspn( strrev( $url ), $sep );
1112 if ( $numSepChars ) {
1113 $trail = substr( $url, -$numSepChars ) . $trail;
1114 $url = substr( $url, 0, -$numSepChars );
1117 $url = Sanitizer
::cleanUrl( $url );
1119 # Is this an external image?
1120 $text = $this->maybeMakeExternalImage( $url );
1121 if ( $text === false ) {
1122 # Not an image, make a link
1123 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1124 $this->getExternalLinkAttribs() );
1125 # Register it in the output object...
1126 # Replace unnecessary URL escape codes with their equivalent characters
1127 $pasteurized = self
::replaceUnusualEscapes( $url );
1128 $this->mOutput
->addExternalLink( $pasteurized );
1130 wfProfileOut( __METHOD__
);
1131 return $text . $trail;
1136 * Parse headers and return html
1140 function doHeadings( $text ) {
1141 wfProfileIn( __METHOD__
);
1142 for ( $i = 6; $i >= 1; --$i ) {
1143 $h = str_repeat( '=', $i );
1144 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1145 "<h$i>\\1</h$i>", $text );
1147 wfProfileOut( __METHOD__
);
1152 * Replace single quotes with HTML markup
1154 * @return string the altered text
1156 function doAllQuotes( $text ) {
1157 wfProfileIn( __METHOD__
);
1159 $lines = StringUtils
::explode( "\n", $text );
1160 foreach ( $lines as $line ) {
1161 $outtext .= $this->doQuotes( $line ) . "\n";
1163 $outtext = substr($outtext, 0,-1);
1164 wfProfileOut( __METHOD__
);
1169 * Helper function for doAllQuotes()
1171 public function doQuotes( $text ) {
1172 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1173 if ( count( $arr ) == 1 )
1177 # First, do some preliminary work. This may shift some apostrophes from
1178 # being mark-up to being text. It also counts the number of occurrences
1179 # of bold and italics mark-ups.
1183 foreach ( $arr as $r )
1185 if ( ( $i %
2 ) == 1 )
1187 # If there are ever four apostrophes, assume the first is supposed to
1188 # be text, and the remaining three constitute mark-up for bold text.
1189 if ( strlen( $arr[$i] ) == 4 )
1194 # If there are more than 5 apostrophes in a row, assume they're all
1195 # text except for the last 5.
1196 else if ( strlen( $arr[$i] ) > 5 )
1198 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1201 # Count the number of occurrences of bold and italics mark-ups.
1202 # We are not counting sequences of five apostrophes.
1203 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1204 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1205 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1210 # If there is an odd number of both bold and italics, it is likely
1211 # that one of the bold ones was meant to be an apostrophe followed
1212 # by italics. Which one we cannot know for certain, but it is more
1213 # likely to be one that has a single-letter word before it.
1214 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1217 $firstsingleletterword = -1;
1218 $firstmultiletterword = -1;
1220 foreach ( $arr as $r )
1222 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1224 $x1 = substr ($arr[$i-1], -1);
1225 $x2 = substr ($arr[$i-1], -2, 1);
1227 if ($firstspace == -1) $firstspace = $i;
1228 } else if ($x2 === ' ') {
1229 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1231 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1237 # If there is a single-letter word, use it!
1238 if ($firstsingleletterword > -1)
1240 $arr [ $firstsingleletterword ] = "''";
1241 $arr [ $firstsingleletterword-1 ] .= "'";
1243 # If not, but there's a multi-letter word, use that one.
1244 else if ($firstmultiletterword > -1)
1246 $arr [ $firstmultiletterword ] = "''";
1247 $arr [ $firstmultiletterword-1 ] .= "'";
1249 # ... otherwise use the first one that has neither.
1250 # (notice that it is possible for all three to be -1 if, for example,
1251 # there is only one pentuple-apostrophe in the line)
1252 else if ($firstspace > -1)
1254 $arr [ $firstspace ] = "''";
1255 $arr [ $firstspace-1 ] .= "'";
1259 # Now let's actually convert our apostrophic mush to HTML!
1264 foreach ($arr as $r)
1268 if ($state === 'both')
1275 if (strlen ($r) == 2)
1278 { $output .= '</i>'; $state = ''; }
1279 else if ($state === 'bi')
1280 { $output .= '</i>'; $state = 'b'; }
1281 else if ($state === 'ib')
1282 { $output .= '</b></i><b>'; $state = 'b'; }
1283 else if ($state === 'both')
1284 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1285 else # $state can be 'b' or ''
1286 { $output .= '<i>'; $state .= 'i'; }
1288 else if (strlen ($r) == 3)
1291 { $output .= '</b>'; $state = ''; }
1292 else if ($state === 'bi')
1293 { $output .= '</i></b><i>'; $state = 'i'; }
1294 else if ($state === 'ib')
1295 { $output .= '</b>'; $state = 'i'; }
1296 else if ($state === 'both')
1297 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1298 else # $state can be 'i' or ''
1299 { $output .= '<b>'; $state .= 'b'; }
1301 else if (strlen ($r) == 5)
1304 { $output .= '</b><i>'; $state = 'i'; }
1305 else if ($state === 'i')
1306 { $output .= '</i><b>'; $state = 'b'; }
1307 else if ($state === 'bi')
1308 { $output .= '</i></b>'; $state = ''; }
1309 else if ($state === 'ib')
1310 { $output .= '</b></i>'; $state = ''; }
1311 else if ($state === 'both')
1312 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1313 else # ($state == '')
1314 { $buffer = ''; $state = 'both'; }
1319 # Now close all remaining tags. Notice that the order is important.
1320 if ($state === 'b' ||
$state === 'ib')
1322 if ($state === 'i' ||
$state === 'bi' ||
$state === 'ib')
1324 if ($state === 'bi')
1326 # There might be lonely ''''', so make sure we have a buffer
1327 if ($state === 'both' && $buffer)
1328 $output .= '<b><i>'.$buffer.'</i></b>';
1334 * Replace external links (REL)
1336 * Note: this is all very hackish and the order of execution matters a lot.
1337 * Make sure to run maintenance/parserTests.php if you change this code.
1341 function replaceExternalLinks( $text ) {
1343 wfProfileIn( __METHOD__
);
1345 $sk = $this->mOptions
->getSkin();
1347 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1348 $s = array_shift( $bits );
1351 while ( $i<count( $bits ) ) {
1353 $protocol = $bits[$i++
];
1354 $text = $bits[$i++
];
1355 $trail = $bits[$i++
];
1357 # The characters '<' and '>' (which were escaped by
1358 # removeHTMLtags()) should not be included in
1359 # URLs, per RFC 2396.
1361 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1362 $text = substr($url, $m2[0][1]) . ' ' . $text;
1363 $url = substr($url, 0, $m2[0][1]);
1366 # If the link text is an image URL, replace it with an <img> tag
1367 # This happened by accident in the original parser, but some people used it extensively
1368 $img = $this->maybeMakeExternalImage( $text );
1369 if ( $img !== false ) {
1375 # Set linktype for CSS - if URL==text, link is essentially free
1376 $linktype = ($text === $url) ?
'free' : 'text';
1378 # No link text, e.g. [http://domain.tld/some.link]
1379 if ( $text == '' ) {
1380 # Autonumber if allowed. See bug #5918
1381 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1382 $langObj = $this->getFunctionLang();
1383 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1384 $linktype = 'autonumber';
1386 # Otherwise just use the URL
1387 $text = htmlspecialchars( $url );
1391 # Have link text, e.g. [http://domain.tld/some.link text]s
1393 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1396 $text = $wgContLang->markNoConversion($text);
1398 $url = Sanitizer
::cleanUrl( $url );
1400 if ( $this->mOptions
->mExternalLinkTarget
) {
1401 $attribs = array( 'target' => $this->mOptions
->mExternalLinkTarget
);
1406 # Use the encoded URL
1407 # This means that users can paste URLs directly into the text
1408 # Funny characters like ö aren't valid in URLs anyway
1409 # This was changed in August 2004
1410 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->getExternalLinkAttribs() )
1413 # Register link in the output object.
1414 # Replace unnecessary URL escape codes with the referenced character
1415 # This prevents spammers from hiding links from the filters
1416 $pasteurized = self
::replaceUnusualEscapes( $url );
1417 $this->mOutput
->addExternalLink( $pasteurized );
1420 wfProfileOut( __METHOD__
);
1424 function getExternalLinkAttribs() {
1426 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1427 $ns = $this->mTitle
->getNamespace();
1428 if( $wgNoFollowLinks && !in_array($ns, $wgNoFollowNsExceptions) ) {
1429 $attribs['rel'] = 'nofollow';
1431 if ( $this->mOptions
->getExternalLinkTarget() ) {
1432 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1439 * Replace unusual URL escape codes with their equivalent characters
1443 * @todo This can merge genuinely required bits in the path or query string,
1444 * breaking legit URLs. A proper fix would treat the various parts of
1445 * the URL differently; as a workaround, just use the output for
1446 * statistical records, not for actual linking/output.
1448 static function replaceUnusualEscapes( $url ) {
1449 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1450 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1454 * Callback function used in replaceUnusualEscapes().
1455 * Replaces unusual URL escape codes with their equivalent character
1459 private static function replaceUnusualEscapesCallback( $matches ) {
1460 $char = urldecode( $matches[0] );
1461 $ord = ord( $char );
1462 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1463 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1464 // No, shouldn't be escaped
1467 // Yes, leave it escaped
1473 * make an image if it's allowed, either through the global
1474 * option, through the exception, or through the on-wiki whitelist
1477 function maybeMakeExternalImage( $url ) {
1478 $sk = $this->mOptions
->getSkin();
1479 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1480 $imagesexception = !empty($imagesfrom);
1482 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1483 if( $imagesexception && is_array( $imagesfrom ) ) {
1484 $imagematch = false;
1485 foreach( $imagesfrom as $match ) {
1486 if( strpos( $url, $match ) === 0 ) {
1491 } elseif( $imagesexception ) {
1492 $imagematch = (strpos( $url, $imagesfrom ) === 0);
1494 $imagematch = false;
1496 if ( $this->mOptions
->getAllowExternalImages()
1497 ||
( $imagesexception && $imagematch ) ) {
1498 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1500 $text = $sk->makeExternalImage( $url );
1503 if( !$text && $this->mOptions
->getEnableImageWhitelist()
1504 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1505 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1506 foreach( $whitelist as $entry ) {
1507 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1508 if( strpos( $entry, '#' ) === 0 ||
$entry === '' )
1510 if( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1511 # Image matches a whitelist entry
1512 $text = $sk->makeExternalImage( $url );
1521 * Process [[ ]] wikilinks
1522 * @return processed text
1526 function replaceInternalLinks( $s ) {
1527 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1532 * Process [[ ]] wikilinks (RIL)
1533 * @return LinkHolderArray
1537 function replaceInternalLinks2( &$s ) {
1540 wfProfileIn( __METHOD__
);
1542 wfProfileIn( __METHOD__
.'-setup' );
1543 static $tc = FALSE, $e1, $e1_img;
1544 # the % is needed to support urlencoded titles as well
1546 $tc = Title
::legalChars() . '#%';
1547 # Match a link having the form [[namespace:link|alternate]]trail
1548 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1549 # Match cases where there is no "]]", which might still be images
1550 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1553 $sk = $this->mOptions
->getSkin();
1554 $holders = new LinkHolderArray( $this );
1556 #split the entire text string on occurences of [[
1557 $a = StringUtils
::explode( '[[', ' ' . $s );
1558 #get the first element (all text up to first [[), and remove the space we added
1561 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1562 $s = substr( $s, 1 );
1564 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1566 if ( $useLinkPrefixExtension ) {
1567 # Match the end of a line for a word that's not followed by whitespace,
1568 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1569 $e2 = wfMsgForContent( 'linkprefix' );
1572 if( is_null( $this->mTitle
) ) {
1573 wfProfileOut( __METHOD__
.'-setup' );
1574 wfProfileOut( __METHOD__
);
1575 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1577 $nottalk = !$this->mTitle
->isTalkPage();
1579 if ( $useLinkPrefixExtension ) {
1581 if ( preg_match( $e2, $s, $m ) ) {
1582 $first_prefix = $m[2];
1584 $first_prefix = false;
1590 if($wgContLang->hasVariants()) {
1591 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1593 $selflink = array($this->mTitle
->getPrefixedText());
1595 $useSubpages = $this->areSubpagesAllowed();
1596 wfProfileOut( __METHOD__
.'-setup' );
1598 # Loop for each link
1599 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1600 # Check for excessive memory usage
1601 if ( $holders->isBig() ) {
1603 # Do the existence check, replace the link holders and clear the array
1604 $holders->replace( $s );
1608 if ( $useLinkPrefixExtension ) {
1609 wfProfileIn( __METHOD__
.'-prefixhandling' );
1610 if ( preg_match( $e2, $s, $m ) ) {
1618 $prefix = $first_prefix;
1619 $first_prefix = false;
1621 wfProfileOut( __METHOD__
.'-prefixhandling' );
1624 $might_be_img = false;
1626 wfProfileIn( __METHOD__
."-e1" );
1627 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1629 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1630 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1631 # the real problem is with the $e1 regex
1634 # Still some problems for cases where the ] is meant to be outside punctuation,
1635 # and no image is in sight. See bug 2095.
1638 substr( $m[3], 0, 1 ) === ']' &&
1639 strpos($text, '[') !== false
1642 $text .= ']'; # so that replaceExternalLinks($text) works later
1643 $m[3] = substr( $m[3], 1 );
1645 # fix up urlencoded title texts
1646 if( strpos( $m[1], '%' ) !== false ) {
1647 # Should anchors '#' also be rejected?
1648 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1651 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1652 $might_be_img = true;
1654 if ( strpos( $m[1], '%' ) !== false ) {
1655 $m[1] = urldecode($m[1]);
1658 } else { # Invalid form; output directly
1659 $s .= $prefix . '[[' . $line ;
1660 wfProfileOut( __METHOD__
."-e1" );
1663 wfProfileOut( __METHOD__
."-e1" );
1664 wfProfileIn( __METHOD__
."-misc" );
1666 # Don't allow internal links to pages containing
1667 # PROTO: where PROTO is a valid URL protocol; these
1668 # should be external links.
1669 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1670 $s .= $prefix . '[[' . $line ;
1671 wfProfileOut( __METHOD__
."-misc" );
1675 # Make subpage if necessary
1676 if( $useSubpages ) {
1677 $link = $this->maybeDoSubpageLink( $m[1], $text );
1682 $noforce = (substr($m[1], 0, 1) !== ':');
1684 # Strip off leading ':'
1685 $link = substr($link, 1);
1688 wfProfileOut( __METHOD__
."-misc" );
1689 wfProfileIn( __METHOD__
."-title" );
1690 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1692 $s .= $prefix . '[[' . $line;
1693 wfProfileOut( __METHOD__
."-title" );
1697 $ns = $nt->getNamespace();
1698 $iw = $nt->getInterWiki();
1699 wfProfileOut( __METHOD__
."-title" );
1701 if ($might_be_img) { # if this is actually an invalid link
1702 wfProfileIn( __METHOD__
."-might_be_img" );
1703 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1706 #look at the next 'line' to see if we can close it there
1708 $next_line = $a->current();
1709 if ( $next_line === false ||
$next_line === null ) {
1712 $m = explode( ']]', $next_line, 3 );
1713 if ( count( $m ) == 3 ) {
1714 # the first ]] closes the inner link, the second the image
1716 $text .= "[[{$m[0]}]]{$m[1]}";
1719 } elseif ( count( $m ) == 2 ) {
1720 #if there's exactly one ]] that's fine, we'll keep looking
1721 $text .= "[[{$m[0]}]]{$m[1]}";
1723 #if $next_line is invalid too, we need look no further
1724 $text .= '[[' . $next_line;
1729 # we couldn't find the end of this imageLink, so output it raw
1730 #but don't ignore what might be perfectly normal links in the text we've examined
1731 $holders->merge( $this->replaceInternalLinks2( $text ) );
1732 $s .= "{$prefix}[[$link|$text";
1733 # note: no $trail, because without an end, there *is* no trail
1734 wfProfileOut( __METHOD__
."-might_be_img" );
1737 } else { #it's not an image, so output it raw
1738 $s .= "{$prefix}[[$link|$text";
1739 # note: no $trail, because without an end, there *is* no trail
1740 wfProfileOut( __METHOD__
."-might_be_img" );
1743 wfProfileOut( __METHOD__
."-might_be_img" );
1746 $wasblank = ( '' == $text );
1747 if( $wasblank ) $text = $link;
1749 # Link not escaped by : , create the various objects
1753 wfProfileIn( __METHOD__
."-interwiki" );
1754 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1755 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1756 $s = rtrim($s . $prefix);
1757 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1758 wfProfileOut( __METHOD__
."-interwiki" );
1761 wfProfileOut( __METHOD__
."-interwiki" );
1763 if ( $ns == NS_IMAGE
) {
1764 wfProfileIn( __METHOD__
."-image" );
1765 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1766 # recursively parse links inside the image caption
1767 # actually, this will parse them in any other parameters, too,
1768 # but it might be hard to fix that, and it doesn't matter ATM
1769 $text = $this->replaceExternalLinks($text);
1770 $holders->merge( $this->replaceInternalLinks2( $text ) );
1772 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1773 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1775 $this->mOutput
->addImage( $nt->getDBkey() );
1776 wfProfileOut( __METHOD__
."-image" );
1781 if ( $ns == NS_CATEGORY
) {
1782 wfProfileIn( __METHOD__
."-category" );
1783 $s = rtrim($s . "\n"); # bug 87
1786 $sortkey = $this->getDefaultSort();
1790 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1791 $sortkey = str_replace( "\n", '', $sortkey );
1792 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1793 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1796 * Strip the whitespace Category links produce, see bug 87
1797 * @todo We might want to use trim($tmp, "\n") here.
1799 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1801 wfProfileOut( __METHOD__
."-category" );
1806 # Self-link checking
1807 if( $nt->getFragment() === '' && $nt->getNamespace() != NS_SPECIAL
) {
1808 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1809 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1814 # Special and Media are pseudo-namespaces; no pages actually exist in them
1815 if( $ns == NS_MEDIA
) {
1816 # Give extensions a chance to select the file revision for us
1817 $skip = $time = false;
1818 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1820 $link = $sk->link( $nt );
1822 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1824 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1825 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1826 $this->mOutput
->addImage( $nt->getDBkey() );
1828 } elseif( $ns == NS_SPECIAL
) {
1829 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
1830 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1832 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1835 } elseif( $ns == NS_IMAGE
) {
1836 $img = wfFindFile( $nt );
1838 // Force a blue link if the file exists; may be a remote
1839 // upload on the shared repository, and we want to see its
1840 // auto-generated page.
1841 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1842 $this->mOutput
->addLink( $nt );
1846 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1848 wfProfileOut( __METHOD__
);
1853 * Make a link placeholder. The text returned can be later resolved to a real link with
1854 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1855 * parsing of interwiki links, and secondly to allow all existence checks and
1856 * article length checks (for stub links) to be bundled into a single query.
1860 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1861 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1865 * Render a forced-blue link inline; protect against double expansion of
1866 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1867 * Since this little disaster has to split off the trail text to avoid
1868 * breaking URLs in the following text without breaking trails on the
1869 * wiki links, it's been made into a horrible function.
1872 * @param string $text
1873 * @param string $query
1874 * @param string $trail
1875 * @param string $prefix
1876 * @return string HTML-wikitext mix oh yuck
1878 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1879 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1880 $sk = $this->mOptions
->getSkin();
1881 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1882 return $this->armorLinks( $link ) . $trail;
1886 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1887 * going to go through further parsing steps before inline URL expansion.
1889 * Not needed quite as much as it used to be since free links are a bit
1890 * more sensible these days. But bracketed links are still an issue.
1892 * @param string more-or-less HTML
1893 * @return string less-or-more HTML with NOPARSE bits
1895 function armorLinks( $text ) {
1896 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1897 "{$this->mUniqPrefix}NOPARSE$1", $text );
1901 * Return true if subpage links should be expanded on this page.
1904 function areSubpagesAllowed() {
1905 # Some namespaces don't allow subpages
1906 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1910 * Handle link to subpage if necessary
1911 * @param string $target the source of the link
1912 * @param string &$text the link text, modified as necessary
1913 * @return string the full name of the link
1916 function maybeDoSubpageLink($target, &$text) {
1919 # :Foobar -- override special treatment of prefix (images, language links)
1920 # /Foobar -- convert to CurrentPage/Foobar
1921 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1922 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1923 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1925 wfProfileIn( __METHOD__
);
1926 $ret = $target; # default return value is no change
1928 # Some namespaces don't allow subpages,
1929 # so only perform processing if subpages are allowed
1930 if( $this->areSubpagesAllowed() ) {
1931 $hash = strpos( $target, '#' );
1932 if( $hash !== false ) {
1933 $suffix = substr( $target, $hash );
1934 $target = substr( $target, 0, $hash );
1939 $target = trim( $target );
1940 # Look at the first character
1941 if( $target != '' && $target{0} === '/' ) {
1942 # / at end means we don't want the slash to be shown
1944 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1945 if( $trailingSlashes ) {
1946 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1948 $noslash = substr( $target, 1 );
1951 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1952 if( '' === $text ) {
1953 $text = $target . $suffix;
1954 } # this might be changed for ugliness reasons
1956 # check for .. subpage backlinks
1958 $nodotdot = $target;
1959 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1961 $nodotdot = substr( $nodotdot, 3 );
1963 if($dotdotcount > 0) {
1964 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1965 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1966 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1967 # / at the end means don't show full path
1968 if( substr( $nodotdot, -1, 1 ) === '/' ) {
1969 $nodotdot = substr( $nodotdot, 0, -1 );
1970 if( '' === $text ) {
1971 $text = $nodotdot . $suffix;
1974 $nodotdot = trim( $nodotdot );
1975 if( $nodotdot != '' ) {
1976 $ret .= '/' . $nodotdot;
1984 wfProfileOut( __METHOD__
);
1989 * Used by doBlockLevels()
1992 /* private */ function closeParagraph() {
1994 if ( '' != $this->mLastSection
) {
1995 $result = '</' . $this->mLastSection
. ">\n";
1997 $this->mInPre
= false;
1998 $this->mLastSection
= '';
2001 # getCommon() returns the length of the longest common substring
2002 # of both arguments, starting at the beginning of both.
2004 /* private */ function getCommon( $st1, $st2 ) {
2005 $fl = strlen( $st1 );
2006 $shorter = strlen( $st2 );
2007 if ( $fl < $shorter ) { $shorter = $fl; }
2009 for ( $i = 0; $i < $shorter; ++
$i ) {
2010 if ( $st1{$i} != $st2{$i} ) { break; }
2014 # These next three functions open, continue, and close the list
2015 # element appropriate to the prefix character passed into them.
2017 /* private */ function openList( $char ) {
2018 $result = $this->closeParagraph();
2020 if ( '*' === $char ) { $result .= '<ul><li>'; }
2021 else if ( '#' === $char ) { $result .= '<ol><li>'; }
2022 else if ( ':' === $char ) { $result .= '<dl><dd>'; }
2023 else if ( ';' === $char ) {
2024 $result .= '<dl><dt>';
2025 $this->mDTopen
= true;
2027 else { $result = '<!-- ERR 1 -->'; }
2032 /* private */ function nextItem( $char ) {
2033 if ( '*' === $char ||
'#' === $char ) { return '</li><li>'; }
2034 else if ( ':' === $char ||
';' === $char ) {
2036 if ( $this->mDTopen
) { $close = '</dt>'; }
2037 if ( ';' === $char ) {
2038 $this->mDTopen
= true;
2039 return $close . '<dt>';
2041 $this->mDTopen
= false;
2042 return $close . '<dd>';
2045 return '<!-- ERR 2 -->';
2048 /* private */ function closeList( $char ) {
2049 if ( '*' === $char ) { $text = '</li></ul>'; }
2050 else if ( '#' === $char ) { $text = '</li></ol>'; }
2051 else if ( ':' === $char ) {
2052 if ( $this->mDTopen
) {
2053 $this->mDTopen
= false;
2054 $text = '</dt></dl>';
2056 $text = '</dd></dl>';
2059 else { return '<!-- ERR 3 -->'; }
2065 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2068 * @return string the lists rendered as HTML
2070 function doBlockLevels( $text, $linestart ) {
2071 wfProfileIn( __METHOD__
);
2073 # Parsing through the text line by line. The main thing
2074 # happening here is handling of block-level elements p, pre,
2075 # and making lists from lines starting with * # : etc.
2077 $textLines = StringUtils
::explode( "\n", $text );
2079 $lastPrefix = $output = '';
2080 $this->mDTopen
= $inBlockElem = false;
2082 $paragraphStack = false;
2084 foreach ( $textLines as $oLine ) {
2086 if ( !$linestart ) {
2092 $lastPrefixLength = strlen( $lastPrefix );
2093 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2094 $preOpenMatch = preg_match('/<pre/i', $oLine );
2095 if ( !$this->mInPre
) {
2096 # Multiple prefixes may abut each other for nested lists.
2097 $prefixLength = strspn( $oLine, '*#:;' );
2098 $prefix = substr( $oLine, 0, $prefixLength );
2101 $prefix2 = str_replace( ';', ':', $prefix );
2102 $t = substr( $oLine, $prefixLength );
2103 $this->mInPre
= (bool)$preOpenMatch;
2105 # Don't interpret any other prefixes in preformatted text
2107 $prefix = $prefix2 = '';
2112 if( $prefixLength && $lastPrefix === $prefix2 ) {
2113 # Same as the last item, so no need to deal with nesting or opening stuff
2114 $output .= $this->nextItem( substr( $prefix, -1 ) );
2115 $paragraphStack = false;
2117 if ( substr( $prefix, -1 ) === ';') {
2118 # The one nasty exception: definition lists work like this:
2119 # ; title : definition text
2120 # So we check for : in the remainder text to split up the
2121 # title and definition, without b0rking links.
2123 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2125 $output .= $term . $this->nextItem( ':' );
2128 } elseif( $prefixLength ||
$lastPrefixLength ) {
2129 # Either open or close a level...
2130 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2131 $paragraphStack = false;
2133 while( $commonPrefixLength < $lastPrefixLength ) {
2134 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2135 --$lastPrefixLength;
2137 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2138 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2140 while ( $prefixLength > $commonPrefixLength ) {
2141 $char = substr( $prefix, $commonPrefixLength, 1 );
2142 $output .= $this->openList( $char );
2144 if ( ';' === $char ) {
2145 # FIXME: This is dupe of code above
2146 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2148 $output .= $term . $this->nextItem( ':' );
2151 ++
$commonPrefixLength;
2153 $lastPrefix = $prefix2;
2155 if( 0 == $prefixLength ) {
2156 wfProfileIn( __METHOD__
."-paragraph" );
2157 # No prefix (not in list)--go to paragraph mode
2158 // XXX: use a stack for nestable elements like span, table and div
2159 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2160 $closematch = preg_match(
2161 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2162 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2163 if ( $openmatch or $closematch ) {
2164 $paragraphStack = false;
2165 #Â TODO bug 5718: paragraph closed
2166 $output .= $this->closeParagraph();
2167 if ( $preOpenMatch and !$preCloseMatch ) {
2168 $this->mInPre
= true;
2170 if ( $closematch ) {
2171 $inBlockElem = false;
2173 $inBlockElem = true;
2175 } else if ( !$inBlockElem && !$this->mInPre
) {
2176 if ( ' ' == $t{0} and ( $this->mLastSection
=== 'pre' or trim($t) != '' ) ) {
2178 if ($this->mLastSection
!== 'pre') {
2179 $paragraphStack = false;
2180 $output .= $this->closeParagraph().'<pre>';
2181 $this->mLastSection
= 'pre';
2183 $t = substr( $t, 1 );
2186 if ( '' == trim($t) ) {
2187 if ( $paragraphStack ) {
2188 $output .= $paragraphStack.'<br />';
2189 $paragraphStack = false;
2190 $this->mLastSection
= 'p';
2192 if ($this->mLastSection
!== 'p' ) {
2193 $output .= $this->closeParagraph();
2194 $this->mLastSection
= '';
2195 $paragraphStack = '<p>';
2197 $paragraphStack = '</p><p>';
2201 if ( $paragraphStack ) {
2202 $output .= $paragraphStack;
2203 $paragraphStack = false;
2204 $this->mLastSection
= 'p';
2205 } else if ($this->mLastSection
!== 'p') {
2206 $output .= $this->closeParagraph().'<p>';
2207 $this->mLastSection
= 'p';
2212 wfProfileOut( __METHOD__
."-paragraph" );
2214 // somewhere above we forget to get out of pre block (bug 785)
2215 if($preCloseMatch && $this->mInPre
) {
2216 $this->mInPre
= false;
2218 if ($paragraphStack === false) {
2222 while ( $prefixLength ) {
2223 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2226 if ( '' != $this->mLastSection
) {
2227 $output .= '</' . $this->mLastSection
. '>';
2228 $this->mLastSection
= '';
2231 wfProfileOut( __METHOD__
);
2236 * Split up a string on ':', ignoring any occurences inside tags
2237 * to prevent illegal overlapping.
2238 * @param string $str the string to split
2239 * @param string &$before set to everything before the ':'
2240 * @param string &$after set to everything after the ':'
2241 * return string the position of the ':', or false if none found
2243 function findColonNoLinks($str, &$before, &$after) {
2244 wfProfileIn( __METHOD__
);
2246 $pos = strpos( $str, ':' );
2247 if( $pos === false ) {
2249 wfProfileOut( __METHOD__
);
2253 $lt = strpos( $str, '<' );
2254 if( $lt === false ||
$lt > $pos ) {
2255 // Easy; no tag nesting to worry about
2256 $before = substr( $str, 0, $pos );
2257 $after = substr( $str, $pos+
1 );
2258 wfProfileOut( __METHOD__
);
2262 // Ugly state machine to walk through avoiding tags.
2263 $state = self
::COLON_STATE_TEXT
;
2265 $len = strlen( $str );
2266 for( $i = 0; $i < $len; $i++
) {
2270 // (Using the number is a performance hack for common cases)
2271 case 0: // self::COLON_STATE_TEXT:
2274 // Could be either a <start> tag or an </end> tag
2275 $state = self
::COLON_STATE_TAGSTART
;
2280 $before = substr( $str, 0, $i );
2281 $after = substr( $str, $i +
1 );
2282 wfProfileOut( __METHOD__
);
2285 // Embedded in a tag; don't break it.
2288 // Skip ahead looking for something interesting
2289 $colon = strpos( $str, ':', $i );
2290 if( $colon === false ) {
2291 // Nothing else interesting
2292 wfProfileOut( __METHOD__
);
2295 $lt = strpos( $str, '<', $i );
2296 if( $stack === 0 ) {
2297 if( $lt === false ||
$colon < $lt ) {
2299 $before = substr( $str, 0, $colon );
2300 $after = substr( $str, $colon +
1 );
2301 wfProfileOut( __METHOD__
);
2305 if( $lt === false ) {
2306 // Nothing else interesting to find; abort!
2307 // We're nested, but there's no close tags left. Abort!
2310 // Skip ahead to next tag start
2312 $state = self
::COLON_STATE_TAGSTART
;
2315 case 1: // self::COLON_STATE_TAG:
2320 $state = self
::COLON_STATE_TEXT
;
2323 // Slash may be followed by >?
2324 $state = self
::COLON_STATE_TAGSLASH
;
2330 case 2: // self::COLON_STATE_TAGSTART:
2333 $state = self
::COLON_STATE_CLOSETAG
;
2336 $state = self
::COLON_STATE_COMMENT
;
2339 // Illegal early close? This shouldn't happen D:
2340 $state = self
::COLON_STATE_TEXT
;
2343 $state = self
::COLON_STATE_TAG
;
2346 case 3: // self::COLON_STATE_CLOSETAG:
2351 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2352 wfProfileOut( __METHOD__
);
2355 $state = self
::COLON_STATE_TEXT
;
2358 case self
::COLON_STATE_TAGSLASH
:
2360 // Yes, a self-closed tag <blah/>
2361 $state = self
::COLON_STATE_TEXT
;
2363 // Probably we're jumping the gun, and this is an attribute
2364 $state = self
::COLON_STATE_TAG
;
2367 case 5: // self::COLON_STATE_COMMENT:
2369 $state = self
::COLON_STATE_COMMENTDASH
;
2372 case self
::COLON_STATE_COMMENTDASH
:
2374 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2376 $state = self
::COLON_STATE_COMMENT
;
2379 case self
::COLON_STATE_COMMENTDASHDASH
:
2381 $state = self
::COLON_STATE_TEXT
;
2383 $state = self
::COLON_STATE_COMMENT
;
2387 throw new MWException( "State machine error in " . __METHOD__
);
2391 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2394 wfProfileOut( __METHOD__
);
2399 * Return value of a magic variable (like PAGENAME)
2403 function getVariableValue( $index ) {
2404 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2407 * Some of these require message or data lookups and can be
2408 * expensive to check many times.
2410 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2411 if ( isset( $this->mVarCache
[$index] ) ) {
2412 return $this->mVarCache
[$index];
2416 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2417 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2420 global $wgLocaltimezone;
2421 if ( isset( $wgLocaltimezone ) ) {
2422 $oldtz = getenv( 'TZ' );
2423 putenv( 'TZ='.$wgLocaltimezone );
2426 wfSuppressWarnings(); // E_STRICT system time bitching
2427 $localTimestamp = date( 'YmdHis', $ts );
2428 $localMonth = date( 'm', $ts );
2429 $localMonthName = date( 'n', $ts );
2430 $localDay = date( 'j', $ts );
2431 $localDay2 = date( 'd', $ts );
2432 $localDayOfWeek = date( 'w', $ts );
2433 $localWeek = date( 'W', $ts );
2434 $localYear = date( 'Y', $ts );
2435 $localHour = date( 'H', $ts );
2436 if ( isset( $wgLocaltimezone ) ) {
2437 putenv( 'TZ='.$oldtz );
2439 wfRestoreWarnings();
2442 case 'currentmonth':
2443 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2444 case 'currentmonthname':
2445 return $this->mVarCache
[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2446 case 'currentmonthnamegen':
2447 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2448 case 'currentmonthabbrev':
2449 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2451 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2453 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2455 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth );
2456 case 'localmonthname':
2457 return $this->mVarCache
[$index] = $wgContLang->getMonthName( $localMonthName );
2458 case 'localmonthnamegen':
2459 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2460 case 'localmonthabbrev':
2461 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2463 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay );
2465 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay2 );
2467 return wfEscapeWikiText( $this->mTitle
->getText() );
2469 return $this->mTitle
->getPartialURL();
2470 case 'fullpagename':
2471 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2472 case 'fullpagenamee':
2473 return $this->mTitle
->getPrefixedURL();
2475 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2476 case 'subpagenamee':
2477 return $this->mTitle
->getSubpageUrlForm();
2478 case 'basepagename':
2479 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2480 case 'basepagenamee':
2481 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2482 case 'talkpagename':
2483 if( $this->mTitle
->canTalk() ) {
2484 $talkPage = $this->mTitle
->getTalkPage();
2485 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2489 case 'talkpagenamee':
2490 if( $this->mTitle
->canTalk() ) {
2491 $talkPage = $this->mTitle
->getTalkPage();
2492 return $talkPage->getPrefixedUrl();
2496 case 'subjectpagename':
2497 $subjPage = $this->mTitle
->getSubjectPage();
2498 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2499 case 'subjectpagenamee':
2500 $subjPage = $this->mTitle
->getSubjectPage();
2501 return $subjPage->getPrefixedUrl();
2503 // Let the edit saving system know we should parse the page
2504 // *after* a revision ID has been assigned.
2505 $this->mOutput
->setFlag( 'vary-revision' );
2506 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2507 return $this->mRevisionId
;
2509 // Let the edit saving system know we should parse the page
2510 // *after* a revision ID has been assigned. This is for null edits.
2511 $this->mOutput
->setFlag( 'vary-revision' );
2512 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2513 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2514 case 'revisionday2':
2515 // Let the edit saving system know we should parse the page
2516 // *after* a revision ID has been assigned. This is for null edits.
2517 $this->mOutput
->setFlag( 'vary-revision' );
2518 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2519 return substr( $this->getRevisionTimestamp(), 6, 2 );
2520 case 'revisionmonth':
2521 // Let the edit saving system know we should parse the page
2522 // *after* a revision ID has been assigned. This is for null edits.
2523 $this->mOutput
->setFlag( 'vary-revision' );
2524 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2525 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2526 case 'revisionyear':
2527 // Let the edit saving system know we should parse the page
2528 // *after* a revision ID has been assigned. This is for null edits.
2529 $this->mOutput
->setFlag( 'vary-revision' );
2530 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2531 return substr( $this->getRevisionTimestamp(), 0, 4 );
2532 case 'revisiontimestamp':
2533 // Let the edit saving system know we should parse the page
2534 // *after* a revision ID has been assigned. This is for null edits.
2535 $this->mOutput
->setFlag( 'vary-revision' );
2536 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2537 return $this->getRevisionTimestamp();
2539 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2541 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2543 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2545 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2546 case 'subjectspace':
2547 return $this->mTitle
->getSubjectNsText();
2548 case 'subjectspacee':
2549 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2550 case 'currentdayname':
2551 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2553 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2555 return $this->mVarCache
[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2557 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2559 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2560 // int to remove the padding
2561 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2563 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2564 case 'localdayname':
2565 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2567 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localYear, true );
2569 return $this->mVarCache
[$index] = $wgContLang->time( $localTimestamp, false, false );
2571 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localHour, true );
2573 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2574 // int to remove the padding
2575 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)$localWeek );
2577 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDayOfWeek );
2578 case 'numberofarticles':
2579 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2580 case 'numberoffiles':
2581 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::images() );
2582 case 'numberofusers':
2583 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::users() );
2584 case 'numberofpages':
2585 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2586 case 'numberofadmins':
2587 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::numberingroup('sysop') );
2588 case 'numberofedits':
2589 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2590 case 'currenttimestamp':
2591 return $this->mVarCache
[$index] = wfTimestamp( TS_MW
, $ts );
2592 case 'localtimestamp':
2593 return $this->mVarCache
[$index] = $localTimestamp;
2594 case 'currentversion':
2595 return $this->mVarCache
[$index] = SpecialVersion
::getVersion();
2601 return $wgServerName;
2603 return $wgScriptPath;
2604 case 'directionmark':
2605 return $wgContLang->getDirMark();
2606 case 'contentlanguage':
2607 global $wgContLanguageCode;
2608 return $wgContLanguageCode;
2611 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret ) ) )
2619 * initialise the magic variables (like CURRENTMONTHNAME)
2623 function initialiseVariables() {
2624 wfProfileIn( __METHOD__
);
2625 $variableIDs = MagicWord
::getVariableIDs();
2627 $this->mVariables
= new MagicWordArray( $variableIDs );
2628 wfProfileOut( __METHOD__
);
2632 * Preprocess some wikitext and return the document tree.
2633 * This is the ghost of replace_variables().
2635 * @param string $text The text to parse
2636 * @param integer flags Bitwise combination of:
2637 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2638 * included. Default is to assume a direct page view.
2640 * The generated DOM tree must depend only on the input text and the flags.
2641 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2643 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2644 * change in the DOM tree for a given text, must be passed through the section identifier
2645 * in the section edit link and thus back to extractSections().
2647 * The output of this function is currently only cached in process memory, but a persistent
2648 * cache may be implemented at a later date which takes further advantage of these strict
2649 * dependency requirements.
2653 function preprocessToDom ( $text, $flags = 0 ) {
2654 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2659 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2661 public static function splitWhitespace( $s ) {
2662 $ltrimmed = ltrim( $s );
2663 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2664 $trimmed = rtrim( $ltrimmed );
2665 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2667 $w2 = substr( $ltrimmed, -$diff );
2671 return array( $w1, $trimmed, $w2 );
2675 * Replace magic variables, templates, and template arguments
2676 * with the appropriate text. Templates are substituted recursively,
2677 * taking care to avoid infinite loops.
2679 * Note that the substitution depends on value of $mOutputType:
2680 * self::OT_WIKI: only {{subst:}} templates
2681 * self::OT_PREPROCESS: templates but not extension tags
2682 * self::OT_HTML: all templates and extension tags
2684 * @param string $tex The text to transform
2685 * @param PPFrame $frame Object describing the arguments passed to the template.
2686 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2687 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2688 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2691 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2692 # Prevent too big inclusions
2693 if( strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2697 wfProfileIn( __METHOD__
);
2699 if ( $frame === false ) {
2700 $frame = $this->getPreprocessor()->newFrame();
2701 } elseif ( !( $frame instanceof PPFrame
) ) {
2702 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2703 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2706 $dom = $this->preprocessToDom( $text );
2707 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2708 $text = $frame->expand( $dom, $flags );
2710 wfProfileOut( __METHOD__
);
2714 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2715 static function createAssocArgs( $args ) {
2716 $assocArgs = array();
2718 foreach( $args as $arg ) {
2719 $eqpos = strpos( $arg, '=' );
2720 if ( $eqpos === false ) {
2721 $assocArgs[$index++
] = $arg;
2723 $name = trim( substr( $arg, 0, $eqpos ) );
2724 $value = trim( substr( $arg, $eqpos+
1 ) );
2725 if ( $value === false ) {
2728 if ( $name !== false ) {
2729 $assocArgs[$name] = $value;
2738 * Warn the user when a parser limitation is reached
2739 * Will warn at most once the user per limitation type
2741 * @param string $limitationType, should be one of:
2742 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2743 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2744 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2745 * @params int $current, $max When an explicit limit has been
2746 * exceeded, provide the values (optional)
2748 function limitationWarn( $limitationType, $current=null, $max=null) {
2749 $msgName = $limitationType . '-warning';
2750 //does no harm if $current and $max are present but are unnecessary for the message
2751 $warning = wfMsgExt( $msgName, array( 'parsemag', 'escape' ), $current, $max );
2752 $this->mOutput
->addWarning( $warning );
2753 $cat = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( $limitationType . '-category' ) );
2755 $this->mOutput
->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
2760 * Return the text of a template, after recursively
2761 * replacing any variables or templates within the template.
2763 * @param array $piece The parts of the template
2764 * $piece['title']: the title, i.e. the part before the |
2765 * $piece['parts']: the parameter array
2766 * $piece['lineStart']: whether the brace was at the start of a line
2767 * @param PPFrame The current frame, contains template arguments
2768 * @return string the text of the template
2771 function braceSubstitution( $piece, $frame ) {
2772 global $wgContLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2773 wfProfileIn( __METHOD__
);
2774 wfProfileIn( __METHOD__
.'-setup' );
2777 $found = false; # $text has been filled
2778 $nowiki = false; # wiki markup in $text should be escaped
2779 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2780 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2781 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2782 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2784 # Title object, where $text came from
2787 # $part1 is the bit before the first |, and must contain only title characters.
2788 # Various prefixes will be stripped from it later.
2789 $titleWithSpaces = $frame->expand( $piece['title'] );
2790 $part1 = trim( $titleWithSpaces );
2793 # Original title text preserved for various purposes
2794 $originalTitle = $part1;
2796 # $args is a list of argument nodes, starting from index 0, not including $part1
2797 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2798 wfProfileOut( __METHOD__
.'-setup' );
2801 wfProfileIn( __METHOD__
.'-modifiers' );
2803 $mwSubst = MagicWord
::get( 'subst' );
2804 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2805 # One of two possibilities is true:
2806 # 1) Found SUBST but not in the PST phase
2807 # 2) Didn't find SUBST and in the PST phase
2808 # In either case, return without further processing
2809 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2816 if ( !$found && $args->getLength() == 0 ) {
2817 $id = $this->mVariables
->matchStartToEnd( $part1 );
2818 if ( $id !== false ) {
2819 $text = $this->getVariableValue( $id );
2820 if (MagicWord
::getCacheTTL($id)>-1)
2821 $this->mOutput
->mContainsOldMagic
= true;
2826 # MSG, MSGNW and RAW
2829 $mwMsgnw = MagicWord
::get( 'msgnw' );
2830 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2833 # Remove obsolete MSG:
2834 $mwMsg = MagicWord
::get( 'msg' );
2835 $mwMsg->matchStartAndRemove( $part1 );
2839 $mwRaw = MagicWord
::get( 'raw' );
2840 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2841 $forceRawInterwiki = true;
2844 wfProfileOut( __METHOD__
.'-modifiers' );
2848 wfProfileIn( __METHOD__
. '-pfunc' );
2850 $colonPos = strpos( $part1, ':' );
2851 if ( $colonPos !== false ) {
2852 # Case sensitive functions
2853 $function = substr( $part1, 0, $colonPos );
2854 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2855 $function = $this->mFunctionSynonyms
[1][$function];
2857 # Case insensitive functions
2858 $function = strtolower( $function );
2859 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2860 $function = $this->mFunctionSynonyms
[0][$function];
2866 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2867 $initialArgs = array( &$this );
2868 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2869 if ( $flags & SFH_OBJECT_ARGS
) {
2870 # Add a frame parameter, and pass the arguments as an array
2871 $allArgs = $initialArgs;
2872 $allArgs[] = $frame;
2873 for ( $i = 0; $i < $args->getLength(); $i++
) {
2874 $funcArgs[] = $args->item( $i );
2876 $allArgs[] = $funcArgs;
2878 # Convert arguments to plain text
2879 for ( $i = 0; $i < $args->getLength(); $i++
) {
2880 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2882 $allArgs = array_merge( $initialArgs, $funcArgs );
2885 # Workaround for PHP bug 35229 and similar
2886 if ( !is_callable( $callback ) ) {
2887 throw new MWException( "Tag hook for $function is not callable\n" );
2889 $result = call_user_func_array( $callback, $allArgs );
2892 $preprocessFlags = 0;
2894 if ( is_array( $result ) ) {
2895 if ( isset( $result[0] ) ) {
2897 unset( $result[0] );
2900 // Extract flags into the local scope
2901 // This allows callers to set flags such as nowiki, found, etc.
2907 $text = $this->preprocessToDom( $text, $preprocessFlags );
2912 wfProfileOut( __METHOD__
. '-pfunc' );
2915 # Finish mangling title and then check for loops.
2916 # Set $title to a Title object and $titleText to the PDBK
2919 # Split the title into page and subpage
2921 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2922 if ($subpage !== '') {
2923 $ns = $this->mTitle
->getNamespace();
2925 $title = Title
::newFromText( $part1, $ns );
2927 $titleText = $title->getPrefixedText();
2928 # Check for language variants if the template is not found
2929 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2930 $wgContLang->findVariantLink( $part1, $title, true );
2932 # Do infinite loop check
2933 if ( !$frame->loopCheck( $title ) ) {
2935 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2936 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2938 # Do recursion depth check
2939 $limit = $this->mOptions
->getMaxTemplateDepth();
2940 if ( $frame->depth
>= $limit ) {
2942 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2947 # Load from database
2948 if ( !$found && $title ) {
2949 wfProfileIn( __METHOD__
. '-loadtpl' );
2950 if ( !$title->isExternal() ) {
2951 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2952 $text = SpecialPage
::capturePath( $title );
2953 if ( is_string( $text ) ) {
2956 $this->disableCache();
2958 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2959 $found = false; //access denied
2960 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
2962 list( $text, $title ) = $this->getTemplateDom( $title );
2963 if ( $text !== false ) {
2969 # If the title is valid but undisplayable, make a link to it
2970 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2971 $text = "[[:$titleText]]";
2974 } elseif ( $title->isTrans() ) {
2975 // Interwiki transclusion
2976 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2977 $text = $this->interwikiTransclude( $title, 'render' );
2980 $text = $this->interwikiTransclude( $title, 'raw' );
2981 // Preprocess it like a template
2982 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2987 wfProfileOut( __METHOD__
. '-loadtpl' );
2990 # If we haven't found text to substitute by now, we're done
2991 # Recover the source wikitext and return it
2993 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2994 wfProfileOut( __METHOD__
);
2995 return array( 'object' => $text );
2998 # Expand DOM-style return values in a child frame
2999 if ( $isChildObj ) {
3000 # Clean up argument array
3001 $newFrame = $frame->newChild( $args, $title );
3004 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3005 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3006 # Expansion is eligible for the empty-frame cache
3007 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3008 $text = $this->mTplExpandCache
[$titleText];
3010 $text = $newFrame->expand( $text );
3011 $this->mTplExpandCache
[$titleText] = $text;
3014 # Uncached expansion
3015 $text = $newFrame->expand( $text );
3018 if ( $isLocalObj && $nowiki ) {
3019 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3020 $isLocalObj = false;
3023 # Replace raw HTML by a placeholder
3024 # Add a blank line preceding, to prevent it from mucking up
3025 # immediately preceding headings
3027 $text = "\n\n" . $this->insertStripItem( $text );
3029 # Escape nowiki-style return values
3030 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3031 $text = wfEscapeWikiText( $text );
3033 # Bug 529: if the template begins with a table or block-level
3034 # element, it should be treated as beginning a new line.
3035 # This behaviour is somewhat controversial.
3036 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3037 $text = "\n" . $text;
3040 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3041 # Error, oversize inclusion
3042 $text = "[[$originalTitle]]" .
3043 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3044 $this->limitationWarn( 'post-expand-template-inclusion' );
3047 if ( $isLocalObj ) {
3048 $ret = array( 'object' => $text );
3050 $ret = array( 'text' => $text );
3053 wfProfileOut( __METHOD__
);
3058 * Get the semi-parsed DOM representation of a template with a given title,
3059 * and its redirect destination title. Cached.
3061 function getTemplateDom( $title ) {
3062 $cacheTitle = $title;
3063 $titleText = $title->getPrefixedDBkey();
3065 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3066 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3067 $title = Title
::makeTitle( $ns, $dbk );
3068 $titleText = $title->getPrefixedDBkey();
3070 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3071 return array( $this->mTplDomCache
[$titleText], $title );
3074 // Cache miss, go to the database
3075 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3077 if ( $text === false ) {
3078 $this->mTplDomCache
[$titleText] = false;
3079 return array( false, $title );
3082 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3083 $this->mTplDomCache
[ $titleText ] = $dom;
3085 if (! $title->equals($cacheTitle)) {
3086 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3087 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3090 return array( $dom, $title );
3094 * Fetch the unparsed text of a template and register a reference to it.
3096 function fetchTemplateAndTitle( $title ) {
3097 $templateCb = $this->mOptions
->getTemplateCallback();
3098 $stuff = call_user_func( $templateCb, $title, $this );
3099 $text = $stuff['text'];
3100 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3101 if ( isset( $stuff['deps'] ) ) {
3102 foreach ( $stuff['deps'] as $dep ) {
3103 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3106 return array($text,$finalTitle);
3109 function fetchTemplate( $title ) {
3110 $rv = $this->fetchTemplateAndTitle($title);
3115 * Static function to get a template
3116 * Can be overridden via ParserOptions::setTemplateCallback().
3118 static function statelessFetchTemplate( $title, $parser=false ) {
3119 $text = $skip = false;
3120 $finalTitle = $title;
3123 // Loop to fetch the article, with up to 1 redirect
3124 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3125 # Give extensions a chance to select the revision instead
3126 $id = false; // Assume current
3127 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3133 'page_id' => $title->getArticleID(),
3137 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3138 $rev_id = $rev ?
$rev->getId() : 0;
3139 // If there is no current revision, there is no page
3140 if( $id === false && !$rev ) {
3141 $linkCache = LinkCache
::singleton();
3142 $linkCache->addBadLinkObj( $title );
3147 'page_id' => $title->getArticleID(),
3148 'rev_id' => $rev_id );
3151 $text = $rev->getText();
3152 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3154 $message = $wgContLang->lcfirst( $title->getText() );
3155 $text = wfMsgForContentNoTrans( $message );
3156 if( wfEmptyMsg( $message, $text ) ) {
3163 if ( $text === false ) {
3167 $finalTitle = $title;
3168 $title = Title
::newFromRedirect( $text );
3172 'finalTitle' => $finalTitle,
3177 * Transclude an interwiki link.
3179 function interwikiTransclude( $title, $action ) {
3180 global $wgEnableScaryTranscluding;
3182 if (!$wgEnableScaryTranscluding)
3183 return wfMsg('scarytranscludedisabled');
3185 $url = $title->getFullUrl( "action=$action" );
3187 if (strlen($url) > 255)
3188 return wfMsg('scarytranscludetoolong');
3189 return $this->fetchScaryTemplateMaybeFromCache($url);
3192 function fetchScaryTemplateMaybeFromCache($url) {
3193 global $wgTranscludeCacheExpiry;
3194 $dbr = wfGetDB(DB_SLAVE
);
3195 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3196 array('tc_url' => $url));
3198 $time = $obj->tc_time
;
3199 $text = $obj->tc_contents
;
3200 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3205 $text = Http
::get($url);
3207 return wfMsg('scarytranscludefailed', $url);
3209 $dbw = wfGetDB(DB_MASTER
);
3210 $dbw->replace('transcache', array('tc_url'), array(
3212 'tc_time' => time(),
3213 'tc_contents' => $text));
3219 * Triple brace replacement -- used for template arguments
3222 function argSubstitution( $piece, $frame ) {
3223 wfProfileIn( __METHOD__
);
3226 $parts = $piece['parts'];
3227 $nameWithSpaces = $frame->expand( $piece['title'] );
3228 $argName = trim( $nameWithSpaces );
3230 $text = $frame->getArgument( $argName );
3231 if ( $text === false && $parts->getLength() > 0
3235 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3238 # No match in frame, use the supplied default
3239 $object = $parts->item( 0 )->getChildren();
3241 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3242 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3243 $this->limitationWarn( 'post-expand-template-argument' );
3246 if ( $text === false && $object === false ) {
3248 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3250 if ( $error !== false ) {
3253 if ( $object !== false ) {
3254 $ret = array( 'object' => $object );
3256 $ret = array( 'text' => $text );
3259 wfProfileOut( __METHOD__
);
3264 * Return the text to be used for a given extension tag.
3265 * This is the ghost of strip().
3267 * @param array $params Associative array of parameters:
3268 * name PPNode for the tag name
3269 * attr PPNode for unparsed text where tag attributes are thought to be
3270 * attributes Optional associative array of parsed attributes
3271 * inner Contents of extension element
3272 * noClose Original text did not have a close tag
3273 * @param PPFrame $frame
3275 function extensionSubstitution( $params, $frame ) {
3276 global $wgRawHtml, $wgContLang;
3278 $name = $frame->expand( $params['name'] );
3279 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3280 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3282 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3284 if ( $this->ot
['html'] ) {
3285 $name = strtolower( $name );
3287 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3288 if ( isset( $params['attributes'] ) ) {
3289 $attributes = $attributes +
$params['attributes'];
3297 throw new MWException( '<html> extension tag encountered unexpectedly' );
3300 $output = Xml
::escapeTagsOnly( $content );
3303 $output = $wgContLang->armourMath(
3304 MathRenderer
::renderMath( $content, $attributes ) );
3307 $output = $this->renderImageGallery( $content, $attributes );
3310 $output = $this->renderPoem( $content, $attributes );
3313 if( isset( $this->mTagHooks
[$name] ) ) {
3314 # Workaround for PHP bug 35229 and similar
3315 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3316 throw new MWException( "Tag hook for $name is not callable\n" );
3318 $output = call_user_func_array( $this->mTagHooks
[$name],
3319 array( $content, $attributes, $this ) );
3321 $output = '<span class="error">Invalid tag extension name: ' .
3322 htmlspecialchars( $name ) . '</span>';
3326 if ( is_null( $attrText ) ) {
3329 if ( isset( $params['attributes'] ) ) {
3330 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3331 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3332 htmlspecialchars( $attrValue ) . '"';
3335 if ( $content === null ) {
3336 $output = "<$name$attrText/>";
3338 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3339 $output = "<$name$attrText>$content$close";
3343 if ( $name === 'html' ||
$name === 'nowiki' ) {
3344 $this->mStripState
->nowiki
->setPair( $marker, $output );
3346 $this->mStripState
->general
->setPair( $marker, $output );
3352 * Increment an include size counter
3354 * @param string $type The type of expansion
3355 * @param integer $size The size of the text
3356 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3358 function incrementIncludeSize( $type, $size ) {
3359 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3362 $this->mIncludeSizes
[$type] +
= $size;
3368 * Increment the expensive function count
3370 * @return boolean False if the limit has been exceeded
3372 function incrementExpensiveFunctionCount() {
3373 global $wgExpensiveParserFunctionLimit;
3374 $this->mExpensiveFunctionCount++
;
3375 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3382 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3383 * Fills $this->mDoubleUnderscores, returns the modified text
3385 function doDoubleUnderscore( $text ) {
3386 // The position of __TOC__ needs to be recorded
3387 $mw = MagicWord
::get( 'toc' );
3388 if( $mw->match( $text ) ) {
3389 $this->mShowToc
= true;
3390 $this->mForceTocPosition
= true;
3392 // Set a placeholder. At the end we'll fill it in with the TOC.
3393 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3395 // Only keep the first one.
3396 $text = $mw->replace( '', $text );
3399 // Now match and remove the rest of them
3400 $mwa = MagicWord
::getDoubleUnderscoreArray();
3401 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3403 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3404 $this->mOutput
->mNoGallery
= true;
3406 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3407 $this->mShowToc
= false;
3409 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3410 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3412 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( 'hidden-category-category' ) );
3413 if ( $containerCategory ) {
3414 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3416 wfDebug( __METHOD__
.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3419 # (bug 8068) Allow control over whether robots index a page.
3421 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3422 # is not desirable, the last one on the page should win.
3423 if( isset( $this->mDoubleUnderscores
['noindex'] ) ) {
3424 $this->mOutput
->setIndexPolicy( 'noindex' );
3425 } elseif( isset( $this->mDoubleUnderscores
['index'] ) ) {
3426 $this->mOutput
->setIndexPolicy( 'index' );
3433 * This function accomplishes several tasks:
3434 * 1) Auto-number headings if that option is enabled
3435 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3436 * 3) Add a Table of contents on the top for users who have enabled the option
3437 * 4) Auto-anchor headings
3439 * It loops through all headlines, collects the necessary data, then splits up the
3440 * string and re-inserts the newly formatted headlines.
3442 * @param string $text
3443 * @param boolean $isMain
3446 function formatHeadings( $text, $isMain=true ) {
3447 global $wgMaxTocLevel, $wgContLang;
3449 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3450 $showEditLink = $this->mOptions
->getEditSection();
3452 // Do not call quickUserCan unless necessary
3453 if( $showEditLink && !$this->mTitle
->quickUserCan( 'edit' ) ) {
3457 # Inhibit editsection links if requested in the page
3458 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3462 # Get all headlines for numbering them and adding funky stuff like [edit]
3463 # links - this is for later, but we need the number of headlines right now
3465 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3467 # if there are fewer than 4 headlines in the article, do not show TOC
3468 # unless it's been explicitly enabled.
3469 $enoughToc = $this->mShowToc
&&
3470 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3472 # Allow user to stipulate that a page should have a "new section"
3473 # link added via __NEWSECTIONLINK__
3474 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3475 $this->mOutput
->setNewSection( true );
3478 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3479 # override above conditions and always show TOC above first header
3480 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3481 $this->mShowToc
= true;
3485 # We need this to perform operations on the HTML
3486 $sk = $this->mOptions
->getSkin();
3492 # Ugh .. the TOC should have neat indentation levels which can be
3493 # passed to the skin functions. These are determined here
3497 $sublevelCount = array();
3498 $levelCount = array();
3504 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3505 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3508 foreach( $matches[3] as $headline ) {
3509 $isTemplate = false;
3511 $sectionIndex = false;
3513 $markerMatches = array();
3514 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3515 $serial = $markerMatches[1];
3516 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3517 $isTemplate = ($titleText != $baseTitleText);
3518 $headline = preg_replace("/^$markerRegex/", "", $headline);
3522 $prevlevel = $level;
3523 $prevtoclevel = $toclevel;
3525 $level = $matches[1][$headlineCount];
3527 if( $doNumberHeadings ||
$enoughToc ) {
3529 if ( $level > $prevlevel ) {
3530 # Increase TOC level
3532 $sublevelCount[$toclevel] = 0;
3533 if( $toclevel<$wgMaxTocLevel ) {
3534 $prevtoclevel = $toclevel;
3535 $toc .= $sk->tocIndent();
3539 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3540 # Decrease TOC level, find level to jump to
3542 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3543 # Can only go down to level 1
3546 for ($i = $toclevel; $i > 0; $i--) {
3547 if ( $levelCount[$i] == $level ) {
3548 # Found last matching level
3552 elseif ( $levelCount[$i] < $level ) {
3553 # Found first matching level below current level
3559 if( $toclevel<$wgMaxTocLevel ) {
3560 if($prevtoclevel < $wgMaxTocLevel) {
3561 # Unindent only if the previous toc level was shown :p
3562 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3563 $prevtoclevel = $toclevel;
3565 $toc .= $sk->tocLineEnd();
3570 # No change in level, end TOC line
3571 if( $toclevel<$wgMaxTocLevel ) {
3572 $toc .= $sk->tocLineEnd();
3576 $levelCount[$toclevel] = $level;
3578 # count number of headlines for each level
3579 @$sublevelCount[$toclevel]++
;
3581 for( $i = 1; $i <= $toclevel; $i++
) {
3582 if( !empty( $sublevelCount[$i] ) ) {
3586 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3592 # The safe header is a version of the header text safe to use for links
3593 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3594 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3596 # Remove link placeholders by the link text.
3597 # <!--LINK number-->
3599 # link text with suffix
3600 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3602 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3603 $tocline = preg_replace(
3604 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3608 $tocline = trim( $tocline );
3610 # For the anchor, strip out HTML-y stuff period
3611 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3612 $safeHeadline = trim( $safeHeadline );
3614 # Save headline for section edit hint before it's escaped
3615 $headlineHint = $safeHeadline;
3616 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3617 # HTML names must be case-insensitively unique (bug 10721)
3618 $arrayKey = strtolower( $safeHeadline );
3620 # count how many in assoc. array so we can track dupes in anchors
3621 isset( $refers[$arrayKey] ) ?
$refers[$arrayKey]++
: $refers[$arrayKey] = 1;
3622 $refcount[$headlineCount] = $refers[$arrayKey];
3624 # Don't number the heading if it is the only one (looks silly)
3625 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3626 # the two are different if the line contains a link
3627 $headline=$numbering . ' ' . $headline;
3630 # Create the anchor for linking from the TOC to the section
3631 $anchor = $safeHeadline;
3632 if($refcount[$headlineCount] > 1 ) {
3633 $anchor .= '_' . $refcount[$headlineCount];
3635 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3636 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3637 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3639 # give headline the correct <h#> tag
3640 if( $showEditLink && $sectionIndex !== false ) {
3642 # Put a T flag in the section identifier, to indicate to extractSections()
3643 # that sections inside <includeonly> should be counted.
3644 $editlink = $sk->doEditSectionLink(Title
::newFromText( $titleText ), "T-$sectionIndex");
3646 $editlink = $sk->doEditSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3651 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3656 $this->mOutput
->setSections( $tocraw );
3658 # Never ever show TOC if no headers
3659 if( $numVisible < 1 ) {
3664 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3665 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3667 $toc = $sk->tocList( $toc );
3670 # split up and insert constructed headlines
3672 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3675 foreach( $blocks as $block ) {
3676 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3677 # This is the [edit] link that appears for the top block of text when
3678 # section editing is enabled
3680 # Disabled because it broke block formatting
3681 # For example, a bullet point in the top line
3682 # $full .= $sk->editSectionLink(0);
3685 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3686 # Top anchor now in skin
3690 if( !empty( $head[$i] ) ) {
3695 if( $this->mForceTocPosition
) {
3696 return str_replace( '<!--MWTOC-->', $toc, $full );
3703 * Transform wiki markup when saving a page by doing \r\n -> \n
3704 * conversion, substitting signatures, {{subst:}} templates, etc.
3706 * @param string $text the text to transform
3707 * @param Title &$title the Title object for the current article
3708 * @param User &$user the User object describing the current user
3709 * @param ParserOptions $options parsing options
3710 * @param bool $clearState whether to clear the parser state first
3711 * @return string the altered wiki markup
3714 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3715 $this->mOptions
= $options;
3716 $this->setTitle( $title );
3717 $this->setOutputType( self
::OT_WIKI
);
3719 if ( $clearState ) {
3720 $this->clearState();
3726 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3727 $text = $this->pstPass2( $text, $user );
3728 $text = $this->mStripState
->unstripBoth( $text );
3733 * Pre-save transform helper function
3736 function pstPass2( $text, $user ) {
3737 global $wgContLang, $wgLocaltimezone;
3739 /* Note: This is the timestamp saved as hardcoded wikitext to
3740 * the database, we use $wgContLang here in order to give
3741 * everyone the same signature and use the default one rather
3742 * than the one selected in each user's preferences.
3744 * (see also bug 12815)
3746 $ts = $this->mOptions
->getTimestamp();
3747 $tz = wfMsgForContent( 'timezone-utc' );
3748 if ( isset( $wgLocaltimezone ) ) {
3749 $unixts = wfTimestamp( TS_UNIX
, $ts );
3750 $oldtz = getenv( 'TZ' );
3751 putenv( 'TZ='.$wgLocaltimezone );
3752 $ts = date( 'YmdHis', $unixts );
3753 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3754 putenv( 'TZ='.$oldtz );
3757 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3759 # Variable replacement
3760 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3761 $text = $this->replaceVariables( $text );
3764 $sigText = $this->getUserSig( $user );
3765 $text = strtr( $text, array(
3767 '~~~~' => "$sigText $d",
3771 # Context links: [[|name]] and [[name (context)|]]
3773 global $wgLegalTitleChars;
3774 $tc = "[$wgLegalTitleChars]";
3775 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3777 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3778 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
3779 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3780 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3782 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3783 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3784 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
3785 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3787 $t = $this->mTitle
->getText();
3789 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3790 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3791 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3792 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3794 # if there's no context, don't bother duplicating the title
3795 $text = preg_replace( $p2, '[[\\1]]', $text );
3798 # Trim trailing whitespace
3799 $text = rtrim( $text );
3805 * Fetch the user's signature text, if any, and normalize to
3806 * validated, ready-to-insert wikitext.
3812 function getUserSig( &$user ) {
3813 global $wgMaxSigChars;
3815 $username = $user->getName();
3816 $nickname = $user->getOption( 'nickname' );
3817 $nickname = $nickname === '' ?
$username : $nickname;
3819 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3820 $nickname = $username;
3821 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3822 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3823 # Sig. might contain markup; validate this
3824 if( $this->validateSig( $nickname ) !== false ) {
3825 # Validated; clean up (if needed) and return it
3826 return $this->cleanSig( $nickname, true );
3828 # Failed to validate; fall back to the default
3829 $nickname = $username;
3830 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
3834 // Make sure nickname doesnt get a sig in a sig
3835 $nickname = $this->cleanSigInSig( $nickname );
3837 # If we're still here, make it a link to the user page
3838 $userText = wfEscapeWikiText( $username );
3839 $nickText = wfEscapeWikiText( $nickname );
3840 if ( $user->isAnon() ) {
3841 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3843 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3848 * Check that the user's signature contains no bad XML
3850 * @param string $text
3851 * @return mixed An expanded string, or false if invalid.
3853 function validateSig( $text ) {
3854 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
3858 * Clean up signature text
3860 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3861 * 2) Substitute all transclusions
3863 * @param string $text
3864 * @param $parsing Whether we're cleaning (preferences save) or parsing
3865 * @return string Signature text
3867 function cleanSig( $text, $parsing = false ) {
3870 $this->clearState();
3871 $this->setTitle( $wgTitle );
3872 $this->mOptions
= new ParserOptions
;
3873 $this->setOutputType
= self
::OT_PREPROCESS
;
3876 # Option to disable this feature
3877 if ( !$this->mOptions
->getCleanSignatures() ) {
3881 # FIXME: regex doesn't respect extension tags or nowiki
3882 # => Move this logic to braceSubstitution()
3883 $substWord = MagicWord
::get( 'subst' );
3884 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3885 $substText = '{{' . $substWord->getSynonym( 0 );
3887 $text = preg_replace( $substRegex, $substText, $text );
3888 $text = $this->cleanSigInSig( $text );
3889 $dom = $this->preprocessToDom( $text );
3890 $frame = $this->getPreprocessor()->newFrame();
3891 $text = $frame->expand( $dom );
3894 $text = $this->mStripState
->unstripBoth( $text );
3901 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3902 * @param string $text
3903 * @return string Signature text with /~{3,5}/ removed
3905 function cleanSigInSig( $text ) {
3906 $text = preg_replace( '/~{3,5}/', '', $text );
3911 * Set up some variables which are usually set up in parse()
3912 * so that an external function can call some class members with confidence
3915 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3916 $this->setTitle( $title );
3917 $this->mOptions
= $options;
3918 $this->setOutputType( $outputType );
3919 if ( $clearState ) {
3920 $this->clearState();
3925 * Wrapper for preprocess()
3927 * @param string $text the text to preprocess
3928 * @param ParserOptions $options options
3932 function transformMsg( $text, $options ) {
3934 static $executing = false;
3936 # Guard against infinite recursion
3942 wfProfileIn(__METHOD__
);
3943 $text = $this->preprocess( $text, $wgTitle, $options );
3946 wfProfileOut(__METHOD__
);
3951 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3952 * The callback should have the following form:
3953 * function myParserHook( $text, $params, &$parser ) { ... }
3955 * Transform and return $text. Use $parser for any required context, e.g. use
3956 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3960 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3961 * @param mixed $callback The callback function (and object) to use for the tag
3963 * @return The old value of the mTagHooks array associated with the hook
3965 function setHook( $tag, $callback ) {
3966 $tag = strtolower( $tag );
3967 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3968 $this->mTagHooks
[$tag] = $callback;
3969 if( !in_array( $tag, $this->mStripList
) ) {
3970 $this->mStripList
[] = $tag;
3976 function setTransparentTagHook( $tag, $callback ) {
3977 $tag = strtolower( $tag );
3978 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3979 $this->mTransparentTagHooks
[$tag] = $callback;
3985 * Remove all tag hooks
3987 function clearTagHooks() {
3988 $this->mTagHooks
= array();
3989 $this->mStripList
= $this->mDefaultStripList
;
3993 * Create a function, e.g. {{sum:1|2|3}}
3994 * The callback function should have the form:
3995 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3997 * Or with SFH_OBJECT_ARGS:
3998 * function myParserFunction( $parser, $frame, $args ) { ... }
4000 * The callback may either return the text result of the function, or an array with the text
4001 * in element 0, and a number of flags in the other elements. The names of the flags are
4002 * specified in the keys. Valid flags are:
4003 * found The text returned is valid, stop processing the template. This
4005 * nowiki Wiki markup in the return value should be escaped
4006 * isHTML The returned text is HTML, armour it against wikitext transformation
4010 * @param string $id The magic word ID
4011 * @param mixed $callback The callback function (and object) to use
4012 * @param integer $flags a combination of the following flags:
4013 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4015 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4016 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4017 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4018 * the arguments, and to control the way they are expanded.
4020 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4021 * arguments, for instance:
4022 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4024 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4025 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4026 * working if/when this is changed.
4028 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4031 * Please read the documentation in includes/parser/Preprocessor.php for more information
4032 * about the methods available in PPFrame and PPNode.
4034 * @return The old callback function for this name, if any
4036 function setFunctionHook( $id, $callback, $flags = 0 ) {
4037 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4038 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4040 # Add to function cache
4041 $mw = MagicWord
::get( $id );
4043 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4045 $synonyms = $mw->getSynonyms();
4046 $sensitive = intval( $mw->isCaseSensitive() );
4048 foreach ( $synonyms as $syn ) {
4050 if ( !$sensitive ) {
4051 $syn = strtolower( $syn );
4054 if ( !( $flags & SFH_NO_HASH
) ) {
4057 # Remove trailing colon
4058 if ( substr( $syn, -1, 1 ) === ':' ) {
4059 $syn = substr( $syn, 0, -1 );
4061 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4067 * Get all registered function hook identifiers
4071 function getFunctionHooks() {
4072 return array_keys( $this->mFunctionHooks
);
4076 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4077 * Placeholders created in Skin::makeLinkObj()
4078 * Returns an array of link CSS classes, indexed by PDBK.
4080 function replaceLinkHolders( &$text, $options = 0 ) {
4081 return $this->mLinkHolders
->replace( $text );
4085 * Replace <!--LINK--> link placeholders with plain text of links
4086 * (not HTML-formatted).
4087 * @param string $text
4090 function replaceLinkHoldersText( $text ) {
4091 return $this->mLinkHolders
->replaceText( $text );
4095 * Tag hook handler for 'pre'.
4097 function renderPreTag( $text, $attribs ) {
4098 // Backwards-compatibility hack
4099 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4101 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4102 return wfOpenElement( 'pre', $attribs ) .
4103 Xml
::escapeTagsOnly( $content ) .
4108 * Renders an image gallery from a text with one line per image.
4109 * text labels may be given by using |-style alternative text. E.g.
4110 * Image:one.jpg|The number "1"
4111 * Image:tree.jpg|A tree
4112 * given as text will return the HTML of a gallery with two images,
4113 * labeled 'The number "1"' and
4116 function renderImageGallery( $text, $params ) {
4117 $ig = new ImageGallery();
4118 $ig->setContextTitle( $this->mTitle
);
4119 $ig->setShowBytes( false );
4120 $ig->setShowFilename( false );
4121 $ig->setParser( $this );
4122 $ig->setHideBadImages();
4123 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4124 $ig->useSkin( $this->mOptions
->getSkin() );
4125 $ig->mRevisionId
= $this->mRevisionId
;
4127 if( isset( $params['caption'] ) ) {
4128 $caption = $params['caption'];
4129 $caption = htmlspecialchars( $caption );
4130 $caption = $this->replaceInternalLinks( $caption );
4131 $ig->setCaptionHtml( $caption );
4133 if( isset( $params['perrow'] ) ) {
4134 $ig->setPerRow( $params['perrow'] );
4136 if( isset( $params['widths'] ) ) {
4137 $ig->setWidths( $params['widths'] );
4139 if( isset( $params['heights'] ) ) {
4140 $ig->setHeights( $params['heights'] );
4143 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4145 $lines = StringUtils
::explode( "\n", $text );
4146 foreach ( $lines as $line ) {
4147 # match lines like these:
4148 # Image:someimage.jpg|This is some image
4150 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4152 if ( count( $matches ) == 0 ) {
4156 if ( strpos( $matches[0], '%' ) !== false )
4157 $matches[1] = urldecode( $matches[1] );
4158 $tp = Title
::newFromText( $matches[1]/*, NS_IMAGE*/ );
4160 if( is_null( $nt ) ) {
4161 # Bogus title. Ignore these so we don't bomb out later.
4164 if ( isset( $matches[3] ) ) {
4165 $label = $matches[3];
4170 $html = $this->recursiveTagParse( trim( $label ) );
4172 $ig->add( $nt, $html );
4174 # Only add real images (bug #5586)
4175 if ( $nt->getNamespace() == NS_IMAGE
) {
4176 $this->mOutput
->addImage( $nt->getDBkey() );
4179 return $ig->toHTML();
4182 /** Renders any text in between <poem></poem> tags
4183 * based on http://www.mediawiki.org/wiki/Extension:Poem
4186 function renderPoem( $in, $param = array() ) {
4188 /* using newlines in the text will cause the parser to add <p> tags,
4189 * which may not be desired in some cases
4191 $nl = array_key_exists( 'compact', $param ) ?
'' : "\n";
4193 $replacer = new DoubleReplacer( ' ', ' ' );
4194 $text = $this->recursiveTagParse( $in );
4195 $text = $this->mStripState
->unstripNoWiki( $text );
4196 // Only strip the very first and very last \n (which trim cannot do)
4197 if( substr( $text, 0, 1 ) == "\n" )
4198 $text = substr( $text, 1 );
4199 if( substr( $text, -1 ) == "\n" )
4200 $text = substr( $text, 0, -1 );
4202 $text = str_replace( "\n", "<br />\n", $text );
4203 $text = preg_replace_callback(
4208 // Pass HTML attributes through to the output.
4209 $attribs = Sanitizer
::validateTagAttributes( $param, 'div' );
4211 // Wrap output in a <div> with "poem" class.
4212 if( array_key_exists( 'class', $attribs ) ) {
4213 $attribs['class'] = 'poem ' . $attribs['class'];
4215 $attribs['class'] = 'poem';
4218 return Xml
::openElement( 'div', $attribs ) . $nl . trim( $text ) . $nl . Xml
::closeElement( 'div' );
4221 function getImageParams( $handler ) {
4223 $handlerClass = get_class( $handler );
4227 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4228 // Initialise static lists
4229 static $internalParamNames = array(
4230 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4231 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4232 'bottom', 'text-bottom' ),
4233 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4234 'upright', 'border', 'link', 'alt' ),
4236 static $internalParamMap;
4237 if ( !$internalParamMap ) {
4238 $internalParamMap = array();
4239 foreach ( $internalParamNames as $type => $names ) {
4240 foreach ( $names as $name ) {
4241 $magicName = str_replace( '-', '_', "img_$name" );
4242 $internalParamMap[$magicName] = array( $type, $name );
4247 // Add handler params
4248 $paramMap = $internalParamMap;
4250 $handlerParamMap = $handler->getParamMap();
4251 foreach ( $handlerParamMap as $magic => $paramName ) {
4252 $paramMap[$magic] = array( 'handler', $paramName );
4255 $this->mImageParams
[$handlerClass] = $paramMap;
4256 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4258 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4262 * Parse image options text and use it to make an image
4263 * @param Title $title
4264 * @param string $options
4265 * @param LinkHolderArray $holders
4267 function makeImage( $title, $options, $holders = false ) {
4268 # Check if the options text is of the form "options|alt text"
4270 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4271 # * left no resizing, just left align. label is used for alt= only
4272 # * right same, but right aligned
4273 # * none same, but not aligned
4274 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4275 # * center center the image
4276 # * framed Keep original image size, no magnify-button.
4277 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4278 # * upright reduce width for upright images, rounded to full __0 px
4279 # * border draw a 1px border around the image
4280 # * alt Text for HTML alt attribute (defaults to empty)
4281 # vertical-align values (no % or length right now):
4291 $parts = StringUtils
::explode( "|", $options );
4292 $sk = $this->mOptions
->getSkin();
4294 # Give extensions a chance to select the file revision for us
4295 $skip = $time = $descQuery = false;
4296 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4299 return $sk->link( $title );
4303 $imagename = $title->getDBkey();
4304 if ( isset( $this->mFileCache
[$imagename][$time] ) ) {
4305 $file = $this->mFileCache
[$imagename][$time];
4307 $file = wfFindFile( $title, $time );
4308 if ( !(count( $this->mFileCache
) <= 1000) ) {
4309 $this->mFileCache
= array();
4311 $this->mFileCache
[$imagename][$time] = $file;
4314 $handler = $file ?
$file->getHandler() : false;
4316 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4318 # Process the input parameters
4320 $params = array( 'frame' => array(), 'handler' => array(),
4321 'horizAlign' => array(), 'vertAlign' => array() );
4322 foreach( $parts as $part ) {
4323 $part = trim( $part );
4324 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4326 if( isset( $paramMap[$magicName] ) ) {
4327 list( $type, $paramName ) = $paramMap[$magicName];
4329 // Special case; width and height come in one variable together
4330 if( $type === 'handler' && $paramName === 'width' ) {
4332 # (bug 13500) In both cases (width/height and width only),
4333 # permit trailing "px" for backward compatibility.
4334 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4335 $width = intval( $m[1] );
4336 $height = intval( $m[2] );
4337 if ( $handler->validateParam( 'width', $width ) ) {
4338 $params[$type]['width'] = $width;
4341 if ( $handler->validateParam( 'height', $height ) ) {
4342 $params[$type]['height'] = $height;
4345 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4346 $width = intval( $value );
4347 if ( $handler->validateParam( 'width', $width ) ) {
4348 $params[$type]['width'] = $width;
4351 } // else no validation -- bug 13436
4353 if ( $type === 'handler' ) {
4354 # Validate handler parameter
4355 $validated = $handler->validateParam( $paramName, $value );
4357 # Validate internal parameters
4358 switch( $paramName ) {
4361 // @fixme - possibly check validity here for
4362 // manualthumb? downstream behavior seems odd with
4363 // missing manual thumbs.
4367 $chars = self
::EXT_LINK_URL_CLASS
;
4368 $prots = $this->mUrlProtocols
;
4369 if ( $value === '' ) {
4370 $paramName = 'no-link';
4373 } elseif ( preg_match( "/^$prots/", $value ) ) {
4374 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4375 $paramName = 'link-url';
4376 $this->mOutput
->addExternalLink( $value );
4380 $linkTitle = Title
::newFromText( $value );
4382 $paramName = 'link-title';
4383 $value = $linkTitle;
4384 $this->mOutput
->addLink( $linkTitle );
4390 // Most other things appear to be empty or numeric...
4391 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4396 $params[$type][$paramName] = $value;
4400 if ( !$validated ) {
4405 # Process alignment parameters
4406 if ( $params['horizAlign'] ) {
4407 $params['frame']['align'] = key( $params['horizAlign'] );
4409 if ( $params['vertAlign'] ) {
4410 $params['frame']['valign'] = key( $params['vertAlign'] );
4413 $params['frame']['caption'] = $caption;
4415 # Strip bad stuff out of the title (tooltip). We can't just use
4416 # replaceLinkHoldersText() here, because if this function is called
4417 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4419 $tooltip = $holders->replaceText( $caption );
4421 $tooltip = $this->replaceLinkHoldersText( $caption );
4424 # make sure there are no placeholders in thumbnail attributes
4425 # that are later expanded to html- so expand them now and
4427 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4428 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4430 $params['frame']['title'] = $tooltip;
4432 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4433 # came to also set the caption, ordinary text after the image -- which
4434 # makes no sense, because that just repeats the text multiple times in
4435 # screen readers. It *also* came to set the title attribute.
4437 # Now that we have an alt attribute, we should not set the alt text to
4438 # equal the caption: that's worse than useless, it just repeats the
4439 # text. This is the framed/thumbnail case. If there's no caption, we
4440 # use the unnamed parameter for alt text as well, just for the time be-
4441 # ing, if the unnamed param is set and the alt param is not.
4443 # For the future, we need to figure out if we want to tweak this more,
4444 # e.g., introducing a title= parameter for the title; ignoring the un-
4445 # named parameter entirely for images without a caption; adding an ex-
4446 # plicit caption= parameter and preserving the old magic unnamed para-
4448 if( $caption !== '' && !isset( $params['frame']['alt'] )
4449 && !isset( $params['frame']['framed'] )
4450 && !isset( $params['frame']['thumbnail'] )
4451 && !isset( $params['frame']['manualthumb'] ) ) {
4452 $params['frame']['alt'] = $tooltip;
4455 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4457 # Linker does the rest
4458 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4460 # Give the handler a chance to modify the parser object
4462 $handler->parserTransformHook( $this, $file );
4469 * Set a flag in the output object indicating that the content is dynamic and
4470 * shouldn't be cached.
4472 function disableCache() {
4473 wfDebug( "Parser output marked as uncacheable.\n" );
4474 $this->mOutput
->mCacheTime
= -1;
4478 * Callback from the Sanitizer for expanding items found in HTML attribute
4479 * values, so they can be safely tested and escaped.
4480 * @param string $text
4481 * @param PPFrame $frame
4485 function attributeStripCallback( &$text, $frame = false ) {
4486 $text = $this->replaceVariables( $text, $frame );
4487 $text = $this->mStripState
->unstripBoth( $text );
4496 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4497 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4498 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4504 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4509 * Break wikitext input into sections, and either pull or replace
4510 * some particular section's text.
4512 * External callers should use the getSection and replaceSection methods.
4514 * @param string $text Page wikitext
4515 * @param string $section A section identifier string of the form:
4516 * <flag1> - <flag2> - ... - <section number>
4518 * Currently the only recognised flag is "T", which means the target section number
4519 * was derived during a template inclusion parse, in other words this is a template
4520 * section edit link. If no flags are given, it was an ordinary section edit link.
4521 * This flag is required to avoid a section numbering mismatch when a section is
4522 * enclosed by <includeonly> (bug 6563).
4524 * The section number 0 pulls the text before the first heading; other numbers will
4525 * pull the given section along with its lower-level subsections. If the section is
4526 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4528 * @param string $mode One of "get" or "replace"
4529 * @param string $newText Replacement text for section data.
4530 * @return string for "get", the extracted section text.
4531 * for "replace", the whole page with the section replaced.
4533 private function extractSections( $text, $section, $mode, $newText='' ) {
4535 $this->clearState();
4536 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4537 $this->mOptions
= new ParserOptions
;
4538 $this->setOutputType( self
::OT_WIKI
);
4540 $frame = $this->getPreprocessor()->newFrame();
4542 // Process section extraction flags
4544 $sectionParts = explode( '-', $section );
4545 $sectionIndex = array_pop( $sectionParts );
4546 foreach ( $sectionParts as $part ) {
4547 if ( $part === 'T' ) {
4548 $flags |
= self
::PTD_FOR_INCLUSION
;
4551 // Preprocess the text
4552 $root = $this->preprocessToDom( $text, $flags );
4554 // <h> nodes indicate section breaks
4555 // They can only occur at the top level, so we can find them by iterating the root's children
4556 $node = $root->getFirstChild();
4558 // Find the target section
4559 if ( $sectionIndex == 0 ) {
4560 // Section zero doesn't nest, level=big
4561 $targetLevel = 1000;
4564 if ( $node->getName() === 'h' ) {
4565 $bits = $node->splitHeading();
4566 if ( $bits['i'] == $sectionIndex ) {
4567 $targetLevel = $bits['level'];
4571 if ( $mode === 'replace' ) {
4572 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4574 $node = $node->getNextSibling();
4580 if ( $mode === 'get' ) {
4587 // Find the end of the section, including nested sections
4589 if ( $node->getName() === 'h' ) {
4590 $bits = $node->splitHeading();
4591 $curLevel = $bits['level'];
4592 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4596 if ( $mode === 'get' ) {
4597 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4599 $node = $node->getNextSibling();
4602 // Write out the remainder (in replace mode only)
4603 if ( $mode === 'replace' ) {
4604 // Output the replacement text
4605 // Add two newlines on -- trailing whitespace in $newText is conventionally
4606 // stripped by the editor, so we need both newlines to restore the paragraph gap
4607 $outText .= $newText . "\n\n";
4609 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4610 $node = $node->getNextSibling();
4614 if ( is_string( $outText ) ) {
4615 // Re-insert stripped tags
4616 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4623 * This function returns the text of a section, specified by a number ($section).
4624 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4625 * the first section before any such heading (section 0).
4627 * If a section contains subsections, these are also returned.
4629 * @param string $text text to look in
4630 * @param string $section section identifier
4631 * @param string $deftext default to return if section is not found
4632 * @return string text of the requested section
4634 public function getSection( $text, $section, $deftext='' ) {
4635 return $this->extractSections( $text, $section, "get", $deftext );
4638 public function replaceSection( $oldtext, $section, $text ) {
4639 return $this->extractSections( $oldtext, $section, "replace", $text );
4643 * Get the timestamp associated with the current revision, adjusted for
4644 * the default server-local timestamp
4646 function getRevisionTimestamp() {
4647 if ( is_null( $this->mRevisionTimestamp
) ) {
4648 wfProfileIn( __METHOD__
);
4650 $dbr = wfGetDB( DB_SLAVE
);
4651 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4652 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4654 // Normalize timestamp to internal MW format for timezone processing.
4655 // This has the added side-effect of replacing a null value with
4656 // the current time, which gives us more sensible behavior for
4658 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4660 // The cryptic '' timezone parameter tells to use the site-default
4661 // timezone offset instead of the user settings.
4663 // Since this value will be saved into the parser cache, served
4664 // to other users, and potentially even used inside links and such,
4665 // it needs to be consistent for all visitors.
4666 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4668 wfProfileOut( __METHOD__
);
4670 return $this->mRevisionTimestamp
;
4674 * Mutator for $mDefaultSort
4676 * @param $sort New value
4678 public function setDefaultSort( $sort ) {
4679 $this->mDefaultSort
= $sort;
4683 * Accessor for $mDefaultSort
4684 * Will use the title/prefixed title if none is set
4688 public function getDefaultSort() {
4689 global $wgCategoryPrefixedDefaultSortkey;
4690 if( $this->mDefaultSort
!== false ) {
4691 return $this->mDefaultSort
;
4692 } elseif ($this->mTitle
->getNamespace() == NS_CATEGORY ||
4693 !$wgCategoryPrefixedDefaultSortkey) {
4694 return $this->mTitle
->getText();
4696 return $this->mTitle
->getPrefixedText();
4701 * Try to guess the section anchor name based on a wikitext fragment
4702 * presumably extracted from a heading, for example "Header" from
4705 public function guessSectionNameFromWikiText( $text ) {
4706 # Strip out wikitext links(they break the anchor)
4707 $text = $this->stripSectionName( $text );
4708 $headline = Sanitizer
::decodeCharReferences( $text );
4710 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4711 $headline = trim( $headline );
4712 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4713 $replacearray = array(
4718 array_keys( $replacearray ),
4719 array_values( $replacearray ),
4724 * Strips a text string of wikitext for use in a section anchor
4726 * Accepts a text string and then removes all wikitext from the
4727 * string and leaves only the resultant text (i.e. the result of
4728 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4729 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4730 * to create valid section anchors by mimicing the output of the
4731 * parser when headings are parsed.
4733 * @param $text string Text string to be stripped of wikitext
4734 * for use in a Section anchor
4735 * @return Filtered text string
4737 public function stripSectionName( $text ) {
4738 # Strip internal link markup
4739 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4740 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4742 # Strip external link markup (FIXME: Not Tolerant to blank link text
4743 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4744 # on how many empty links there are on the page - need to figure that out.
4745 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4747 # Parse wikitext quotes (italics & bold)
4748 $text = $this->doQuotes($text);
4751 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4755 function srvus( $text ) {
4756 return $this->testSrvus( $text, $this->mOutputType
);
4760 * strip/replaceVariables/unstrip for preprocessor regression testing
4762 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
4763 $this->clearState();
4764 if ( ! ( $title instanceof Title
) ) {
4765 $title = Title
::newFromText( $title );
4767 $this->mTitle
= $title;
4768 $this->mOptions
= $options;
4769 $this->setOutputType( $outputType );
4770 $text = $this->replaceVariables( $text );
4771 $text = $this->mStripState
->unstripBoth( $text );
4772 $text = Sanitizer
::removeHTMLtags( $text );
4776 function testPst( $text, $title, $options ) {
4778 if ( ! ( $title instanceof Title
) ) {
4779 $title = Title
::newFromText( $title );
4781 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4784 function testPreprocess( $text, $title, $options ) {
4785 if ( ! ( $title instanceof Title
) ) {
4786 $title = Title
::newFromText( $title );
4788 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
4791 function markerSkipCallback( $s, $callback ) {
4794 while ( $i < strlen( $s ) ) {
4795 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
4796 if ( $markerStart === false ) {
4797 $out .= call_user_func( $callback, substr( $s, $i ) );
4800 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4801 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
4802 if ( $markerEnd === false ) {
4803 $out .= substr( $s, $markerStart );
4806 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
4807 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4817 * @todo document, briefly.
4821 var $general, $nowiki;
4823 function __construct() {
4824 $this->general
= new ReplacementArray
;
4825 $this->nowiki
= new ReplacementArray
;
4828 function unstripGeneral( $text ) {
4829 wfProfileIn( __METHOD__
);
4832 $text = $this->general
->replace( $text );
4833 } while ( $text !== $oldText );
4834 wfProfileOut( __METHOD__
);
4838 function unstripNoWiki( $text ) {
4839 wfProfileIn( __METHOD__
);
4842 $text = $this->nowiki
->replace( $text );
4843 } while ( $text !== $oldText );
4844 wfProfileOut( __METHOD__
);
4848 function unstripBoth( $text ) {
4849 wfProfileIn( __METHOD__
);
4852 $text = $this->general
->replace( $text );
4853 $text = $this->nowiki
->replace( $text );
4854 } while ( $text !== $oldText );
4855 wfProfileOut( __METHOD__
);
4861 * @todo document, briefly.
4864 class OnlyIncludeReplacer
{
4867 function replace( $matches ) {
4868 if ( substr( $matches[1], -1 ) === "\n" ) {
4869 $this->output
.= substr( $matches[1], 0, -1 );
4871 $this->output
.= $matches[1];